0

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
12
  • Where is the line b = B() ? Commented Mar 29, 2014 at 7:34
  • 3
    why did you name a method _init_? Commented Mar 29, 2014 at 7:34
  • 2
    You have a circular import issue, search stackoverflow for other questions about this. Also as Valentin noted, you have a circular logic issue. Even if your code would run, it would cause an infinite loop. Commented Mar 29, 2014 at 7:37
  • 2
    You don't do anything with a in B.__init__(), so postpone creating the A object until you actually need it in some other method. Commented Mar 29, 2014 at 7:47
  • 1
    Circular imports work only if you import the whole module. E.g import A instead of from A import *. Then you would do a = A.A() instead of a = A() and so on. This will fix the error but you will then get RuntimeError: maximum recursion depth exceeded because your script will enter an infinite loop. I guess the main question is what are you trying to achieve here? Commented Mar 29, 2014 at 9:03

1 Answer 1

1

As others have commented (but not answered), you have several logical issues in your code.

  1. Either import A in B or vice versa, but not both. That won't work.
  2. What is the point of both class wanting to instantiate each other at the first place? This will get you an endless loop.
  3. If you instantiate one from the other, you should save the reference to ith, otherwise it will get pointless.
  4. The name _init_ is extremely confusing.
  5. Avoid 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()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.