我在三个文件A.py,B.py和C.py
中有两个类A.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
答案 0 :(得分:1)
正如其他人已评论过(但没有回答),您的代码中存在多个逻辑问题。
A
中的B
,反之亦然,但不能同时导入_init_
。那不行。from ... import *
非常令人困惑。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__()"
。它使你的名字空间变得混乱。我会做一些更正,假设这是你想要的:
A.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()"
B.py
from A import A
from B import B
obj1 = A()
obj2 = B()
C.py现在可以根据需要做到这两点:
{{1}}