在父类中调用`super()`

Bra*_*mon 10 python inheritance super python-3.x

我正在阅读Raymond Hettinger的Python超级()被认为超级! 关于页面,有这个例子:

class Shape:
    def __init__(self, shapename, **kwds):
        self.shapename = shapename
        super().__init__(**kwds)        

class ColoredShape(Shape):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)

cs = ColoredShape(color='red', shapename='circle')
Run Code Online (Sandbox Code Playgroud)

为什么有必要super()Shape这里打电话?我的理解是这个调用object.__init__(**kwds)自从Shape隐式继承object.

即使没有这种说法,我们已经有了

  • shapename在父母的已经建立__init__,
  • color在显式方法覆盖中建立子类,
  • 然后__init__使用super()in 调用父项ColoredShape.

据我所知,删除此行会产生相同的行为和功能:

class Shape:  # (object)
    def __init__(self, shapename, **kwds):
        self.shapename = shapename
        # super().__init__(**kwds)

class ColoredShape(Shape):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)
    def check(self):
        print(self.color)
        print(self.shapename)

cs = ColoredShape(color='red', shapename='circle')

cs.check()
# red
# circle
Run Code Online (Sandbox Code Playgroud)

什么是目的super()之内Shape吗?

use*_*ica 7

重点是合作多重继承.整篇文章的重点是合作多重继承,真的.

你看,Shape除此之外你没有看到任何父母object.当然,但这并不意味着之后MRO上没有任何兄弟姐妹或其他任何东西Shape.super()不仅仅是超级班; 它以方法解析顺序搜索方法的下一个实现.例如,本文后面的一个类是

class MovableColoredShape(ColoredShape, MoveableAdapter):
    pass
Run Code Online (Sandbox Code Playgroud)

在这种情况下,Shape.__init__需要调用super().__init__,或者MoveableAdapter.__init__所有其他__init__调用都将被跳过.


lar*_*sks 5

我看到@ user2357112已经提供了正确的答案.我正在研究一个例子,我会离开这里,因为它几乎就是user2357112所描述的.考虑一下这样的mixin类:

class PositionMixin:
    def __init__(self, x=0, y=0, **kwds):
        super().__init__(**kwds)
        self.x = x
        self.y = y
Run Code Online (Sandbox Code Playgroud)

假设你将它应用到你的ColoredShape班级:

class ColoredShape(Shape, PositionMixin):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)
Run Code Online (Sandbox Code Playgroud)

如果Shape不打电话super.__init__,那么当你这样做时:

myshape = ColoredShape('red', shapename='circle', x=1, y=1)
print(myshape.x, myshape.y)
Run Code Online (Sandbox Code Playgroud)

你得到:

Traceback (most recent call last):
  File "supertest.py", line 18, in <module>
    print (myshape.x, myshape.y)
AttributeError: 'ColoredShape' object has no attribute 'x'
Run Code Online (Sandbox Code Playgroud)

调用方法时super.__init__需要调用形状.__init__PositionMixin