是否可以避免重写子类中的所有超类构造函数参数



>例如,我有一个具有多个参数参数的抽象类Animal,我想创建一个具有Animal所有属性的子类Dog,但具有race的附加属性。据我所知,唯一的方法:

from abc import ABC
class Animal(ABC):
    def __init__(self, name, id, weight):
        self.name = name
        self.id = id
        self.weight = weight
class Dog(Animal):
    def __init__(self, name, id, weight, race) # Only difference is race
        self.race = race
        super().__init__(name, id, weight)

有没有一种方法不包括在Dog的构造函数中复制Animal的所有构造函数参数?当有很多参数时,这可能会变得非常乏味,并且使代码看起来重复。

您可以使用 catch-all 参数,*args**kwargs ,并将它们传递给父参数:

class Dog(Animal):
    def __init__(self, race, *args, **kwargs):
        self.race = race
        super().__init__(*args, **kwargs)

这确实需要您将其他位置参数放在前面:

Dog('mongrel', 'Fido', 42, 81)

您仍然可以在调用时显式命名每个参数,此时顺序不再重要:

Dog(name='Fido', id=42, weight=81, race='mongrel')

最新更新