我在读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}$在Shape
中super()
的目的是什么?在
我看到@user2357112已经提供了一个正确的答案。我正在做一个我想离开这里的例子,因为它几乎就是user2357112所描述的。考虑这样一个mixin类:
假设您将其应用于您的
^{pr2}$ColoredShape
类:如果
Shape
没有调用super.__init__
,那么在执行此操作时:你会得到:
对shape中的
super.__init__
的调用是调用PositionMixin
上的__init__
方法所必需的。在重点是合作多重继承。整篇文章的合作点真的是多重继承。在
你看
Shape
,除了object
,你没有看到任何父母。当然,但这并不意味着在Shape
之后没有任何兄弟姐妹,或其他任何东西。super()
不仅仅是针对超类;它在method resolution order中搜索该方法的下一个实现。例如,本文后面的一个类是在这种情况下,}调用都将被跳过。在
Shape.__init__
需要调用super().__init__
,或者MoveableAdapter.__init__
,所有进一步的{相关问题 更多 >
编程相关推荐