子类 __init__ 没有看到超类有条件地导入模块

Subclass __init__ not seeing superclass conditonally-imported module

我在超类的自初始化实例中有条件导入,但子类看不到模块 (python 2.7):

class A(object):
    def __init__(self, arg1):
        self.attr1 = self.method1(arg1)

    def method1(self, arg1):
        if arg1 == 'foo':
           import amodule
           return amodule.method1()
        else:
            return 'not a dependency on foo'


class B(A):
    def __init__(self, arg1):
        super(B, self).__init__(arg1)
        if arg1 == 'foo':
            self.attr2 = self.method2(self.attr1)

    def method2(self, attr1):
        return amodule.method2()

if __name__=='__main__':
    b = B("foo")
    print b.attr2

这会引发 NameError: global name 'amodule' is not defineda = A("foo") 工作正常

在这种情况下 super 调用不应该执行 import amodule 吗? (并且使用 import 应该将模块放入全局变量中?)

尝试将 import amodule 放在程序的第一行。

原因是在method1中导入了一个module,method2访问不到

如果您遵循您的代码,您会发现您没有到达 method1()。

创建对象时 b = B(foo) 你通过 A.init() 因为调用了 super()。但是,您的 class A() 初始化不包含任何导入语句。然后 A.__init__ 部分完成,然后继续 B.__init__()。下一个命令是调用一个根本没有导入的模块对象。

您可以添加一个辅助方法,检查 arg 是否等于 'Foo',如果是,则导入模块。然后在A.__init__()函数中添加对这个函数的调用。

另一方面,__init__() 工作是初始化变量。它不应该 return 任何东西。

Doesn't import add /amodule/ to the global namespace of the currently executing module? (__main__)?

不,该模块已添加到 sys.modules,但如果它是本地导入的,那么您将不再有任何引用。即名称 amodule 现在不见了。

您仍然可以使用 sys.modules:

访问该模块
def method2(self, attr1):
    import sys
    return sys.modules['amodule'].method2()

或者您可以再次使用 import amodule 导入它,它将从 sys.modules 中提取。


# Here b.py contains
# print('Module b was imported')

def func1():
    print('inside func1')
    import b

def func2():
    print('inside func2')
    import sys
    print(sys.modules['b'])
    import b


def func3():
    print('inside func3')
    import b
    import sys
    print('Deleted b')
    del sys.modules['b']
    import b


func1()
print()
func2()
print()
func3()

演示:

inside func1
Module b was imported

inside func2
<module 'b' from '/Users/ashwini/py/b.py'>

inside func3
Deleted b
Module b was imported