Python 3.x 类继承Python3.6:类似的方法

Python 3.x 类继承Python3.6:类似的方法,python-3.x,inheritance,subclassing,Python 3.x,Inheritance,Subclassing,在类继承方面,我不是最强大的支柱,所以我提出了一个相当愚蠢的问题。按照下面的代码,我将在逻辑上假设在“super”调用之后,指针到达self.example(),它将依次引用同一类中的“example”方法,并将打印值20 class A(object): def __init__(): self.example() def example(self): print(20) class B(A): def __init__():

在类继承方面,我不是最强大的支柱,所以我提出了一个相当愚蠢的问题。按照下面的代码,我将在逻辑上假设在“super”调用之后,指针到达self.example(),它将依次引用同一类中的“example”方法,并将打印值20

class A(object):
    def __init__():
        self.example()
    def example(self):
        print(20)

class B(A):
    def __init__():
       super().__init__()
    def example(self):
        print(10)

x = B()
结果:10

显然不是这样,而是打印了10。有人能解释一下阶级继承的神秘世界吗

class A(object):
    def __init__():
        self.example()
    def example(self):
        print(20)

class B(A):
    def __init__():
       super().__init__()

x = B()
x.example()
看看这个例子

当您从A继承B时,则方法示例被继承到B,您不必将其重写为B。当然,您仍然可以为B编写此方法,然后您将为类B的对象重写“A”方法

您还可以使用一个类与多个其他类进行继承:

class Base(object):
    def __init__(self):
        print("Base created")

class ChildA(Base):
    def __init__(self):
        Base.__init__(self)

class ChildB(Base):
    def __init__(self):
        super(ChildB, self).__init__()

ChildA()
ChildB()

ChildB有另一个调用,与上面示例中使用的调用相同。

实际上,我刚刚编辑了代码(我的子类B继承自超类A)。因此,如果我理解得很好,当我实例化类B时,会调用超类a,而超类a又会调用“example”方法。但是由于类B已经有了“example”方法,它覆盖了类A的“example”方法,并且打印了值10。是的,您很好地理解了它。但是如果B已经有了例如print(20)。然后将覆盖方法
示例
,方法将打印20:)。即使当
A
得到同样的方法打印10。