简体   繁体   English

python 3类继承问题

[英]python 3 class inheritance issue

class A(object):
    def __init__(self):
        self.a = 1

class B(A):
    def __init__(self):
        A.__init__(self)
        self.a = 2
        self.b = 3


class C(object):
    def __init__(self):
        self.a = 4
        self.c = 5

class D(C, B):
    def __init__(self):
        C.__init__(self)
        B.__init__(self)
        self.d = 6

obj = D()
print(obj.a)

My understanding is that python will first search class C then B then A to get a. 我的理解是,python首先会搜索类C,然后是B,然后是A,以获得a。 So print(obj.a) will print out 4 when searching class C. But the answer is 2. This means that Python got self.a = 2 from class B instead of self.a = 4 from class C. Can anyone explain the reasons? 因此,在搜索C类时,print(obj.a)将输出4。但是答案是2。这意味着Python从B类获得了self.a = 2,而不是从C类获得了self.a = 4。原因是什么? Thank you 谢谢

There is no search going on here. 这里没有搜索。 You are making explicit, direct calls to unbound methods, passing in self manually. 您正在对未绑定方法进行显式,直接的调用,并手动传递了self These are simple function calls , nothing more. 这些是简单的函数调用 ,仅此而已。

So this is just a question of tracing the execution order: 因此,这只是跟踪执行顺序的一个问题:

D() -> D.__init__(self)
    C.__init__(self)
        self.a = 4
    B.__init__(self)
        A.__init__(self)
            self.a = 1
        self.a = 2

So a is assigned 4 , then 1 , then 2 . 所以a分配了4 ,然后是1 ,然后是2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM