If a class is inheriting multiple class, why can the superclasses access functions of the other superclasses mutually? Where is the superclass getting the referencing from?
For example
class A():
def a_method(self):
print "I am a"
class B():
def b_method(self):
self.a_method()
class test(A, B):
def test_method(self):
self.b_method()
if __name__ == "__main__":
test_instance = test()
# Will print a_method
test_instance.test_method()
test_b = B()
try:
# will raise exception
test_b.b_method()
except Exception as e:
print e
When you define a class as inheriting from two superclasses
class test(A, B):
it inherits the methods from both superclasses into the same namespace. So, from test()
, you can call both self.a_method()
and self.b_method()
. Your question, I assume, is why calling self.b_method()
works from an instance of test
, but not an instance of B
. It works in test
because both methods are in the same namespace, and when b_method()
calls a_method()
, it can be "seen" from inside the class, and the call succeeds. When instantiating B
, which does not inherit from A
, a_method()
is not visible, and so an exception is raised.
The methods and attributes associated with a class or instance can be examined with dir
:
>>> test_instance = test()
>>> dir(test_instance)
['__doc__', '__module__', 'a_method', 'b_method', 'test_method']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.