我有一个超类的自初始化实例有条件进口,但子类不能看到该模块(Python的2.7):子类__init__没有看到超conditonally导入模块
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 defined
。 a = A("foo")
工程就好了
在这种情况下,super
调用是否应该执行import amodule
? (并且使用import
应该将模块置于全局模式?)
'amodule'是*局部变量*。你为什么会认为你可以在'method2'中访问它?另外,'import'语句不会在全局名称空间中绑定模块名称,而是在任何名称空间中绑定import语句。再次,这将是* local1到'method1' *。 –
不会将当前正在执行的模块的全局名称空间导入add/amodule /? (\_\_主要\_\_)? – cowbert
不,它不会自己检查这个'def f():import sys',然后调用'f()'看看sys是否在全局命名空间中,它不是(除非它已经)。 –