question about imports in a class

J dreadpiratejeff at gmail.com
Mon Dec 7 16:13:25 EST 2009


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

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??

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?

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??

Thanks!  I know enough to be dangerous, so trying to become less so now...

Jeff
-- 

Ogden Nash  - "The trouble with a kitten is that when it grows up,
it's always a cat." -
http://www.brainyquote.com/quotes/authors/o/ogden_nash.html



More information about the Python-list mailing list