2017-09-02 79 views
2

我想知道如何创建一个跳过或不包含父类使用的属性的子类__init__super()但我似乎无法包装我的头在附近。在Python中重写超类时跳过一个参数

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

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正确的属性,除了其不需要名字。

有什么我在代码中丢失?

+1

继承是一个**是一个**的关系。如果你不希望所有'动物'有'名字',不要给他们一个'名字'。 –

回答

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!