NameError while calling the parent class method from another module
在这里,我创建了两个名为test1.py和test2.py的python模块。
在Test1.Py中:
1 2 3 4 5 6 | class c1: pass class c2: def e(self): return c3.x |
在Test2.Py中:
1 2 3 4 5 6 7 8 9 10 | from test1 import * class c3(c1): x = 1 def __init__(self,x): self.x = x class c4(c2): def __init__(self,y): self.y = y |
现在,我需要使用python 3.x解释器调用这些模块:
1 2 3 4 5 6 7 8 9 10 | $ python >>> import test2 as t2 >>> import test1 as t1 >>> a = t2.c4(2) >>> b = t2.c3(4) >>> a.e() Traceback (most recent call last): File"<stdin>", line1, in <module> File"~/test.py", line 6, in e return c3.x NameError: name 'c3' is not defined |
有没有办法解决这个问题?
注:如果我把它们放在单模块test.py中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class c1: pass class c2: def e(self): return c3.x class c3(c1): x = 1 def __init__(self,x): self.x = x class c4(c2): def __init__(self,y): self.y = y |
如果我在解释器中运行它:
1 2 3 4 5 6 | $ python >>> from test import * >>> a = c4(2) >>> b = c3(4) >>> a.e() 1 |
解决方案:是的!最后,这对我也很管用。
我确实喜欢这样:
在Test1.Py中:
1 2 3 4 5 6 7 8 | import test2 class c1: pass class c2: def e(self): return test2.c3.x |
在Test2.Py中:
1 2 3 4 5 6 7 8 9 10 | from test1 import * class c3(c1): x=1 def __init__(self,x): self.x = x class c4(c2): def __init__(self,y): self.y = y |
如果我在python3.x解释器中运行它。我需要这样做:
1 2 3 4 5 6 7 | $ python >>> from test2 import * >>> from test1 import * >>> a = c4(2) >>> b = c3(4) >>> a.e() 1 |
警告:不要这样做:
1 2 3 4 5 | $ python >>> from test1 import * Traceback (most recent call last): ... NameError: name 'c1' is not defined |
类
要修复循环导入,请重构程序以避免循环导入,或者将导入移动到模块末尾(如第二种方法)。
python中的循环(或循环)导入
python中的循环依赖项
https://gist.github.com/databook/40bf84d5870c41a77dc6
https://micropyramid.com/blog/understand-self-and-init-method-in-python-class/
这对我有用。
class c1:
pass
class c2:
def e(self):
a=test2.c3(4)
print a.temp
class c3(test1.c1):
def __init__(self,x):
self.temp=x
class c4(test1.c2):
def __init__(self,y):
self.y = y