Reputation: 97
class A:
def __init__(self):
print('I am A')
class B(A):
def b(self):
print('I am B.b')
class C(A):
def c(self):
x.b()
if __name__ == '__main__':
x = B()
y = C()
y.c()
How does it work when it comes to 'y.c() '? In C.c(), how can the instance x be called without instantiation before? Thanks a lot, if someone can help.
Upvotes: 0
Views: 39
Reputation: 29071
It cannot. In your case, it just happens that when you call x.b()
there is a global variable that happens to be named x
have type B
. It has been initialized at the previous line, with x = B()
.
This code depends on external variables, and will fail in general. If you want to call the objects own method, use self.b()
instead.
Upvotes: 2