Reputation: 18513
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()
class B
to resolve this kind of dependency, does python have similar constructs? Upvotes: 16
Views: 12962
Reputation: 17455
b = B.do_smth()
) are executed while defining the class, not when you create an instance of the classUpvotes: 3
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