Importing modules inside python class

前端 未结 4 1673
孤独总比滥情好
孤独总比滥情好 2020-12-23 09:11

I\'m currently writing a class that needs os, stat and some others.

What\'s the best way to import these modules in my class?

I\'m

4条回答
  •  旧巷少年郎
    2020-12-23 09:23

    If your module will always import another module, always put it at the top as PEP 8 and the other answers indicate. Also, as @delnan mentions in a comment, sys, os, etc. are being used anyway, so it doesn't hurt to import them globally.

    However, there is nothing wrong with conditional imports, if you really only need a module under certain runtime conditions.

    If you only want to import them if the class is defined, like if the class is in an conditional block or another class or method, you can do something like this:

    condition = True
    
    if condition:
        class C(object):
            os = __import__('os')
            def __init__(self):
                print self.os.listdir
    
        C.os
        c = C()
    

    If you only want it to be imported if the class is instantiated, do it in __new__ or __init__.

提交回复
热议问题