python - 在 Python 中覆盖父类(super class)时跳过参数

标签 python class oop inheritance super

我正在尝试弄清楚如何创建一个子类来跳过或不包含父类使用 __init__super() 的属性但是我似乎无法理解它。

我尝试使用以下代码创建一个简单的继承:

class Animal:
    def __init__(self, name, age, sound, **kwargs):
        self.name = name
        self.age = age
        self.sound = sound


        for key, value in kwargs.items():
            setattr(self, key, value)

class Dog(Animal):
    def __init__(self, name, age, sound, *args, **kwargs):
        super().__init__(name, age, sound, **kwargs)


class Lion(Animal):
    def __init__(self, age, sound, *args, **kwargs):
        super().__init__(age, sound, **kwargs)

下面,我尝试打印每个子类(DogLion)的基本属性/信息。它们的共同参数是 nameagesound,它们都出现在我的 Dog 类中(我还添加了 petbreed)。

至于 Lion 类,因为它不需要任何名称(因为它通常生活在野外)我尝试跳过 name 参数所以我没有将其包含在 __init__super() 中。

当我运行文件时,它得到一个

TypeError: __init__() missing 1 required positional argument: 'sound'.

dog = Dog('Lucky', 6, 'Arf! Arf!', pet=True, breed='Shih Tzu')
lion = Lion(10, 'Roar!', wild=True)
print("===Dog===")
print("Name: {}".format(dog.name))
print("Age: {}".format(dog.age))
print(dog.sound)

print("\n===Lion===")    
print("Age: {}".format(lion.age))
print(lion.sound)

所以我尝试解决这些代码并在 Animal 类中设置 sound=""

class Animal:
    def __init__(self, name, age, sound="", **kwargs): # <--I added quotes

这次没有得到错误,但是我没有得到正确的输出。

===Dog===
Name: Lucky
Age: 6
Arf! Arf!

===Lion===
Age: Roar!

我希望 LionDog 一样在适当的位置具有正确的属性,但名称不是必需的。

代码中是否缺少任何内容?

最佳答案

简单的解决方法就是传递一个空的 name,例如“”。那是因为如果你将它们设为强制性,你就不能跳过参数!就像您在 Animal__init__ 中所做的那样。

class Lion(Animal):
    def __init__(self, age, sound, *args, **kwargs):
        super().__init__("", age, sound, **kwargs)

然而,也许更好的解决方法是让 name 成为可选参数,因为 Animal 可能有名字但不需要名字。永远记住类试图抽象“真正的概念”:

class Animal:
    def __init__(self, age, sound, **kwargs):
        self.age = age
        self.sound = sound
        for key, value in kwargs.items():
            setattr(self, key, value)

class Dog(Animal):
    def __init__(self, age, sound, *args, **kwargs):
        super().__init__(age, sound, **kwargs)


class Lion(Animal):
    def __init__(self, age, sound, *args, **kwargs):
        super().__init__(age, sound, **kwargs)

dog = Dog(6, 'Arf! Arf!', name='Lucky', pet=True, breed='Shih Tzu')
lion = Lion(10, 'Roar!', wild=True)
print("===Dog===")
print("Name: {}".format(dog.name))
print("Age: {}".format(dog.age))
print(dog.sound)

print("\n===Lion===")    
print("Age: {}".format(lion.age))
print(lion.sound)

两种方法都给出了正确的结果(据我所知):

===Dog===
Name: Lucky
Age: 6
Arf! Arf!

===Lion===
Age: 10
Roar!

关于python - 在 Python 中覆盖父类(super class)时跳过参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46014080/

相关文章:

python - 如何打乱列表的内容并将第一项保持在同一位置?

java - 从匿名类内部访问变量

Python:将函数应用于数据框列并将结果放入另一列

python - 如何从文本文件中只读取第 26 列?

.net - 如何读取分配给类属性的属性?

objective-c - 在@implementation 中声明变量

oop - 哪种设计模式最适合迭代开发?

C# 简化并可能概括了我的对象克隆方法

c++ - 将成员函数作为参数传递

python - 存储networkx图形对象