Reputation: 3511
I have two classes in three files A.py, B.py and 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"
when I run C.py having:
from B import *
obj = B()
I get the error
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
Upvotes: 0
Views: 71
Reputation: 91017
As others have commented (but not answered), you have several logical issues in your code.
A
in B
or vice versa, but not both. That won't work._init_
is extremely confusing.from ... import *
. It clutters your name space.I'll make some corrections, assuming this is what you want:
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 now can do both as needed:
from A import A
from B import B
obj1 = A()
obj2 = B()
Upvotes: 1