question about imports in a class

J dreadpiratejeff at gmail.com
Mon Dec 7 16:53:46 EST 2009


On Mon, Dec 7, 2009 at 16:13, J <dreadpiratejeff at gmail.com> wrote:

> 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

A little more education and playing around and I'm still not quite
sure how to do this...

for the class i'm writing, I want to import os, sys and wmi globally
for the class...
if I put the import at the beginning of the class, it just dawned on
me that perhaps I still have to explicitly call the function by class:

sysinfo.py

class myclass():
    import os
    def findDMIDecode(self):
        for r,d,f in myclass.os.walk(args)

is that correct?

How about if I have two classes in sysinfo.py and want to import os
globally for BOTH classes to use? Same thing?

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

Still not sure about this, but I DO know where I glaringly screwed up.

Originally, the function that finds the dmidecode executable was doing this:

return dmidecodePath # dmidecodePath is, I learned, a list that
contains the results of
                                 #
self.dmidecodePath=[os.path.normcase(os.path.join(root,file))]

which is wrong, because on the calling side, I was just using the
whole return, which was actually a list, not a string, so this was
fixed simply by:

return dmidecodePath[0]

which now returns simply:

c:\dmidecode\sbin\dmidecode.exe

So that seems correct.

Also, I apologize if my code examples are incomplete.  If they are not
complete "enough" please let me know. I'm doing this for work, and not
sure just how much I can really post without violating any obligations
on my end.. so I'm trying to provide generic examples based on the
code I'm actually trying to write.



-- 

Stephen Leacock  - "I detest life-insurance agents: they always argue
that I shall some day die, which is not so." -
http://www.brainyquote.com/quotes/authors/s/stephen_leacock.html



More information about the Python-list mailing list