我在三个文件A.py,B.py和C.py中有两个类
py
from B import *
class A:
def __init__(self):
b = B()
b._init_()
print "Hello"
B.py
from A import *
class B:
def __init__(self):
a = A()
def _init_(self):
print "hello"
当我运行C.py时:
from B import *
obj = B()
我得到了错误
Traceback (most recent call last):
File "/home/siddhartha/workspace/link/C.py", line 3, in <module>
obj = B()
File "/home/abc/workspace/kinl/B.py", line 5, in __init__
a = A()
File "/home/abc/workspace/kinl/A.py", line 4, in __init__
b = B()
NameError: global name 'B' is not defined
正如其他人评论(但未回答)那样,您的代码中存在几个逻辑问题。
A
,B
反之亦然,但不能两者都导入。那行不通。_init_
非常混乱。from ... import *
。它会使您的名称空间混乱。假设这是您想要的,我将进行一些更正:
A.py:
from B import B # avoid * imports if not needed
class A:
def __init__(self):
self.b = B() # save reference - otherwise it will get lost.
print "Hello from A.__init__()"
B.py
# don't import A!
class B:
def __init__(self):
self.do_init()
# don't call A() - *they* need *us*.
def do_init(self): # properly named
print "hello from B.do_init()"
C.py现在可以根据需要执行以下两项操作:
from A import A
from B import B
obj1 = A()
obj2 = B()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句