0
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.

2
  • 2
    did you mean self.b()? (x is a global variable instantiated in your "__main__" clause). Commented Feb 14, 2019 at 15:06
  • x is a global variable. You created it outside of any function. Commented Feb 14, 2019 at 15:09

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.