J schrieb:
Just a little newbie confusion about OS imports...
Why does this give me an error:
class Windows:
def __init__(self):
'''
Constructor
'''
import os
self.dmidecodePath="" #final path to dmidecode binary
def parseDMI(self):
# First, find dmidecode.exe
for root,dirs,files in os.walk('C:\\'):
for file in files:
if file == "dmidecode.exe":
self.dmidecodePath=[os.path.normcase(os.path.join(root,file))]
return "Found DMIDecode.exe at %s" % self.dmidecodePath
break
Keep in mind that this is very early stage code and does nothing so
far other than telling me where to find dmidecode.exe...
But why does importing in the init not make os available to every
other function in the class? Do I have to import OS into every
function like this:
class ClassA():
def func1(self):
import os
def func2(self):
import os
No, you don't have to - you just import it once at the module level.
Also, when I DO have the import statement inside the function
definition, I'm screwing up the join and getting this:
"C:\\dmidecod\\sbin\\dmidecode.exe"
What am I doing that's creating the two \ characters??
No, you don't screw it up, "\\" is escape-codes for backslash, and I
guess what you see is because you work in the interactive interpreter
that calls repr() on a string when it's displayed - like this:
>>> "\\"
'\\'
>>> print "\\"
\
>>> print repr("\\")
'\\'
Anyway, the first question I'm just asking because I'm still trying to
figure out the heirarchy and how classes work in Python, the other is
because I'm just annoyed...
Also, that brings up a third question:
So in my class, I import OS. Now, in my calling script, do I also
import OS, or will I inheirit OS as part of the class object?
No, it doesn't, and I'd say you better forget about importing inside
functions (methods or normal ones) until you have firmer grasp on how
python namespaces work.
IOW:
script.py
thisclass=myclass(): #where myclass imports os
for r,d,f in os.walk(path)
or would I have to do something like:
for r,d,f in thisclass.os.wall(path)
Or do I just have to also import OS into script.py??
Yes, you do.
Diez
--
http://mail.python.org/mailman/listinfo/python-list