在父类中调用`super()`

2024-06-26 17:43:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我在读Raymond Hettinger的Python’s super() considered super!关于中的一个页面,有个例子:

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

为什么有必要在Shape中调用super()?我的理解是,这调用object.__init__(**kwds),因为Shape隐式继承了object。在

即使没有那份声明,我们已经

  • 已在父级的__init__中建立{}
  • 在显式方法重写中建立了子类的color
  • 然后使用ColoredShape中的super()调用父节点的__init__。在

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

^{pr2}$

Shapesuper()的目的是什么?在


Tags: selfobjectinitdef页面classcolorshape
2条回答

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

class PositionMixin:
    def __init__(self, x=0, y=0, **kwds):
        super().__init__(**kwds)
        self.x = x
        self.y = y

假设您将其应用于您的ColoredShape类:

^{pr2}$

如果Shape没有调用super.__init__,那么在执行此操作时:

myshape = ColoredShape('red', shapename='circle', x=1, y=1)
print(myshape.x, myshape.y)

你会得到:

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

对shape中的super.__init__的调用是调用PositionMixin上的__init__方法所必需的。在

重点是合作多重继承。整篇文章的合作点真的是多重继承。在

你看Shape,除了object,你没有看到任何父母。当然,但这并不意味着在Shape之后没有任何兄弟姐妹,或其他任何东西。super()不仅仅是针对超类;它在method resolution order中搜索该方法的下一个实现。例如,本文后面的一个类是

class MovableColoredShape(ColoredShape, MoveableAdapter):
    pass

在这种情况下,Shape.__init__需要调用super().__init__,或者MoveableAdapter.__init__,所有进一步的{}调用都将被跳过。在

相关问题 更多 >