【问题标题】:Class inheritance python 3.6 : Similar methods类继承python 3.6:类似的方法
【发布时间】:2019-02-28 10:30:53
【问题描述】:

在类继承方面,我不是最强的支柱,所以这是我相当愚蠢的问题。按照下面的代码,我会在逻辑上假设在“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()

结果:1​​0

显然不是这样,而是打印了 10。有人可以对类继承的神秘世界有所了解。

【问题讨论】:

    标签: python-3.x inheritance subclassing


    【解决方案1】:
    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编写这个方法,然后你将覆盖'A'方法,对于对象B类。

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

    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 又会调用“示例”方法。但是由于 B 类已经有 'example' 方法,它会覆盖 A 类的 'example' 方法并打印值 10。
    • 是的,你理解得很好。但是如果 B 已经有例如 print(20)。然后方法 example 将被覆盖,方法将打印 20 :)。即使A 使用相同的方法打印 10。
    猜你喜欢
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 2012-09-27
    • 2011-03-03
    • 2019-11-27
    相关资源
    最近更新 更多