使用 ABC 模块时,关键字参数是一个好习惯吗?

2023-12-26

这个问题是后续this one https://stackoverflow.com/a/54694783/10597450.

使用时super() for 多重继承 https://rhettinger.wordpress.com/2011/05/26/super-considered-super/,建议的方法是使用关键字参数在调用链中传递剩余的值。

当使用ABC模块,在super().__init__ method?

Python 文档中有关的博客文章super()链接到,没有提及任何有关使用的信息**kwargsABC模块。它专注于具体类的多重继承。为了重新表述我的问题,有关使用的建议是否**kwargs with super()适用于使用的类ABC模块?

例如:

from abc import ABC


class GameWeapon(ABC):

    def __init__(self, name, damage, **av):
         super().__init__(**av)
         self.name = name
         self.required_strength = required_strength
         self.damage = damage


class ChargeGun(GameWeapon):

    def __init__(self, name, required_strength, damage, **av):
        super().__init__(name=name,damage=damage,**av)

让我们看一下您提到的博客文章中的特定实例。

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 进行最终调用。因此,博客文章中显示的设计模式并不适用于您的情况。我希望这有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ABC 模块时,关键字参数是一个好习惯吗? 的相关文章

随机推荐