【问题标题】:Skipping a parameter when overriding a superclass in Python在 Python 中覆盖超类时跳过参数
【发布时间】:2018-02-11 08:03:36
【问题描述】:

我正在尝试弄清楚如何使用__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__() 缺少 1 个必需的位置参数:“声音”。

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!

我希望 Lion 在适当的位置具有正确的属性,例如 Dog,除了不需要的名称。

我在代码中遗漏了什么吗?

【问题讨论】:

  • 继承是一种是一种的关系。如果您不希望所有Animals 都拥有names,请不要给他们name

标签: python class oop inheritance super


【解决方案1】:

简单的解决方法是传递一个空的name,例如""None。那是因为如果你强制要求参数,你就不能跳过它们!就像您在 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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 2013-08-19
    • 2021-11-11
    相关资源
    最近更新 更多