在python类中导入模块 [英] Importing modules inside python class

查看:217
本文介绍了在python类中导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个类需要 os stat 以及其他一些类。

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

推荐答案

如果您的模块将始终导入另一个模块,请始终将其置于顶部,如 PEP 8 和其他答案表明。另外,正如@delnan在评论中提到的那样,无论如何都在使用 sys os 等,所以它没有在全球范围内导入它们会有所不利。

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()

如果您只希望在类实例化时导入它,在 __ new __ __ init __ 中进行。

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

这篇关于在python类中导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆