在Python中覆寫超級類時跳過參數

2024-04-29 08:24:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图弄清楚如何创建一个跳过或不包含父类使用__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!

我希望Lion在适当的位置有正确的属性,比如Dog,除了不需要的名称。你知道吗

代码里有我遗漏的东西吗?你知道吗


Tags: nameselfageinitdefkwargsclassprint
1条回答
网友
1楼 · 发布于 2024-04-29 08:24:56

简单的解决方法就是传递一个空的name,例如""None。那是因为如果你强制你的论点,你不能跳过!就像你在__init__Animal中所做的那样。你知道吗

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!

相关问题 更多 >