【问题标题】:Efficient way to import libraries for class methods, in Python在 Python 中为类方法导入库的有效方法
【发布时间】:2016-02-20 20:24:19
【问题描述】:

什么是导入整个类方法中使用的库的 python 和有效方法。

模块级导入为:

from numpy import exp

class A:
    def calc1(self): return exp(1)
    def calc2(self): return exp(1)

方法级导入更干净,但我不确定每次调用方法时是否缓存或导入库:

class B:
    def calc1(self):
        from numpy import exp
        return exp(1)

    def calc2(self):
        from numpy import exp
        return exp(1)

最后,是否有一些类级别的导入如下?

class C:
    from numpy import exp
    def calc1(self): return exp(1)
    def calc2(self): return exp(1)

C().calc1()   # NameError: name 'exp' is not defined

【问题讨论】:

  • 模块级导入通常比方法级导入更清晰 - 您可以轻松查看该文件中导入的所有内容。

标签: python class python-3.x methods import


【解决方案1】:

我相信您可以进行类级别的导入,但是您必须将其称为self.exp 而不仅仅是exp,因为导入的名称将是一个类变量。但我认为总的来说,模块级导入更简单,应该首选,除非你有特定的理由不这样做(例如,循环导入或并不总是可用的导入)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-10
    • 2013-08-07
    • 2020-11-23
    • 2020-12-25
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多