codious
codious

Reputation: 3511

Class initialisation issue python

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

Answers (1)

glglgl
glglgl

Reputation: 91017

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()

Upvotes: 1

Related Questions