【问题标题】:How to import module during class initialization如何在类初始化期间导入模块
【发布时间】:2020-04-05 11:19:30
【问题描述】:

我有一个看起来像这样的类:

class Foo:
    import_extra = false

    def __init__(import_extra):
        if import_extra:
            self.import_extra = true
            import extra

    def do_thing():
        # do some stuff

        if self.import_extra:
            extra.do_extra_stuff()

这个类有一些依赖于extra 的功能,但是我希望能够在我第一次初始化这个类时决定这个功能是否可用,这在开始运行应用程序时会发生一次。不幸的是,我似乎无法弄清楚如何为整个班级导入extra,以便其他方法可以使用它。

我这样设计它是因为extra 模块在某些情况下可能无法导入。 do_thing 经常被调用,所以我希望可以避免将 import 语句放在那里。 有没有我想念的更简单的方法来做到这一点?

【问题讨论】:

  • 如果不知道extra 做了什么或返回了什么,这很难说。 class Foo 有哪些特别重要的功能?
  • 目前的方法行之有效,对吧?
  • 不,当我运行foo = Foo(True); foo.do_thing() 时,当前的方法给了我错误NameError: extra is not defined。我要解决的问题是导入语句在__init__ 方法的范围内,但我希望导入在初始化后可用于整个类。

标签: python python-3.x class import


【解决方案1】:

我找到了解决问题的方法:

from importlib import import_module

class Foo:
    import_os = False
    os = None
    def __init__(self, imp):
        if imp:
            self.import_os = True
            self.os = import_module('os')
    def do_thing(self):
            print("doing thing")
            if self.import_os:
                print(self.os.devnull) # to verify that os has been imported

# check that it does actually work
print("running foo(false)")
f1=Foo(False)
f1.do_thing()
f2=Foo(True)
print("running foo(true)")
f2.do_thing()

输出

running foo(false)
doing thing
running foo(true)
doing thing
/dev/null

这正是我想要的功能。

这里我使用os 而不是extra,这样任何人都可以运行它。 这些答案帮助我弄清楚了:

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 2010-10-31
    • 2016-12-23
    • 1970-01-01
    相关资源
    最近更新 更多