[英]How is the reference of mixin pass to another mixin in python?
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()
. 因此,可以从test()
调用self.a_method()
和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
. 我想,您的问题是为什么调用self.b_method()
可以从test
实例而不是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. 它在test
有效,因为两个方法都在同一个命名空间中,并且当b_method()
调用a_method()
,可以从类内部“看到”它,并且调用成功。 When instantiating B
, which does not inherit from A
, a_method()
is not visible, and so an exception is raised. 当实例化B
,其不从继承A
, a_method()
是不可见的,所以产生一个异常。
The methods and attributes associated with a class or instance can be examined with dir
: 可以使用dir
检查与类或实例关联的方法和属性:
>>> test_instance = test()
>>> dir(test_instance)
['__doc__', '__module__', 'a_method', 'b_method', 'test_method']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.