首页 > python-3.x > 类继承python 3.6:类似的方法

类继承python 3.6:类似的方法 (Class inheritance python 3.6 : Similar methods)

问题

在课堂继承方面,我不是最强大的支柱,所以这里有一个相当愚蠢的问题。按照下面的代码,我会逻辑地假设在'超级'调用之后,指针到达self.example(),而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编写这个方法,然后你将覆盖'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有另一个呼叫,它等同于上面例子中使用的呼叫。

问题

I'm not the strongest pillar when it comes to class inheritance, so here goes my rather silly question. Following the code below, I would logically assume that after the 'super' call, the pointer arrives at self.example() which would in turn refer to the 'example' method in the same class and value 20 will be printed.

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()

Result : 10

This clearly isn't the case and 10 is printed instead. Could someone please shed some light on the mysterious world of class inheritance.

解决方法

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

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

x = B()
x.example()

Look for this, at example.

When you inherit B, from A, then method example is inheritated to B, you not must rewrite this to B. Of course still you can write this method for B, then you will override 'A' method, for objects of class B.

You also can use one class to Inheritance with many others:

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 have another call which is equivalent to that used in example above.

相似信息