简体   繁体   English

在python类中导入模块

[英]Importing modules inside python class

I'm currently writing a class that needs os , stat and some others. 我目前正在写一个需要osstat和其他一些的课程。

What's the best way to import these modules in my class? 在我班上导入这些模块的最佳方法是什么?

I'm thinking about when others will use it, I want the 'dependency' modules to be already imported when the class is instantiated. 我正在考虑其他人何时会使用它,我希望在实例化类时已经导入了'依赖'模块。

Now I'm importing them in my methods, but maybe there's a better solution. 现在我用我的方法导入它们,但也许有更好的解决方案。

If your module will always import another module, always put it at the top as PEP 8 and the other answers indicate. 如果您的模块将始终导入另一个模块,请始终将其作为PEP 8置于顶部,其他答案指示。 Also, as @delnan mentions in a comment, sys , os , etc. are being used anyway, so it doesn't hurt to import them globally. 另外,正如@delnan在评论中提到的那样,无论如何都在使用sysos等,所以在全局导入它们并没有什么坏处。

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__ . 如果您只希望在实例化类时导入它,请在__new____init__

PEP 8 on imports: 进口PEP 8

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. 导入总是放在文件的顶部,就在任何模块注释和文档字符串之后,以及模块全局变量和常量之前。

This makes it easy to see all modules used by the file at hand, and avoids having to replicate the import in several places when a module is used in more than one place. 这样可以轻松查看手头文件使用的所有模块,并避免在多个位置使用模块时在多个位置复制导入。 Everything else (eg function-/method-level imports) should be an absolute exception and needs to be justified well. 其他一切(例如函数/方法级别的导入)应该是一个绝对的例外,并且需要很好地证明其合理性。

import sys
from importlib import import_module

class Foo():

    def __init__(self):

        if self.condition:
            self.importedModule = import_module('moduleName')

        if 'moduleName' in sys.modules:
            self.importedModule.callFunction(params)

        #or

        if self.condition:
            self.importedModule.callFunction(params)

This (search for the section "Imports") official paper states, that import s should normally be put in the top of your source file. 这个 (搜索“Imports”部分)官方文件指出, import s通常应放在源文件的顶部。 I would abide to this rule, apart from special cases. 除了特殊情况,我会遵守这条规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM