让我们看一下您提到的博客文章中的特定实例。
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('red', shapename='circle', radius=30)
TypeError: object.__init__() takes no arguments
当我们创建一个ColoredShape
对象,它将要求我们输入颜色和形状名称。如果您传递意外的关键字参数,则会出现错误。这是因为所有默认类 https://docs.python.org/3/reference/compound_stmts.html#class-definitions(在python 3中)继承自内置类型object
,其中有一个__init__
不需要任何争论。
正如文章指出的那样,object
保证是 MRO 中调用的最后一个类。但是,如果在 Shape 中删除对 super 的调用,则可以毫无问题地添加任意数量的关键字参数,即使它们不会用于任何用途。
class Shape:
def __init__(self, shapename, **kwds):
self.shapename = shapename
class ColoredShape(Shape):
def __init__(self, color, **kwds):
self.color = color
super().__init__(**kwds)
cs = ColoredShape('red', shapename='circle', radius=30, diameter=60)
在您发布的代码中,您继承自 abc,它不会通过 super 对对象的 init 进行最终调用。因此,博客文章中显示的设计模式并不适用于您的情况。我希望这有帮助。