NeoWang
NeoWang

Reputation: 18513

Circular dependency between python classes

In python, class definitions could depend on each other like this:

 # This is not fine
 class A():
     b = B().do_sth();
     def do_sth(self):
         pass

 class B():
     a = A().do_sth();
     def do_sth(self):
         pass

 # This is fine
 def FuncA():
     b = FuncB()

 def FuncB():
     a = FuncA()
  1. Why does clases have this problem, while functions don't?
  2. Languages like C++ have declarations: class B to resolve this kind of dependency, does python have similar constructs?

Upvotes: 16

Views: 12962

Answers (2)

user3159253
user3159253

Reputation: 17455

  1. Classes have these problems because directives on the class level (b = B.do_smth()) are executed while defining the class, not when you create an instance of the class
  2. You may complete the definition of a class lately, after both classes are defined. Python is a dynamic language after all.

Upvotes: 3

user2357112
user2357112

Reputation: 280291

In the function case, we don't actually have to call FuncB to define FuncA. FuncB only needs to be called when we actually call FuncA.

Unlike with functions, the body of a class is executed at definition time. To define class A, we need to actually call a B method, which we can't do because class B isn't defined yet.

To work around this, we can define the classes and then add the properties afterward:

class A(object):
    ...

class B(object):
    ...

A.b = B.do_sth()
B.A = A.do_sth()

If each do_sth call relies on the other call already having been executed, though, this resolution won't work. You will need to perform more extensive changes to fix the problem.

Upvotes: 15

Related Questions