根据下面的类,我试图制作一条允许实例化所有字段的狗,我试过了:
class Animal(object):
def __init__(self, legs=4, animal_type='beast'):
self.legs = legs
self.animal_type = animal_type
class Dog(Animal):
def __init__(self, name=None, owner=None):
self.name = name
self.owner = owner
dog = Dog(legs=4, animal_type='dog', name='Fido', owner='Bob')
print dog.owner
print dog.name
给了TypeError: __init__() got an unexpected keyword argument 'legs'
基于Initializing subclass variable in Python我试过
class Animal(object):
def __init__(self, legs=4, animal_type='beast'):
self.legs = legs
self.animal_type = animal_type
class Dog(Animal):
def __init__(self, legs=None, animal_type=None, name=None, owner=None):
if legs:
self.legs = legs
if animal_type:
self.animal_type = animal_type
self.name = name
self.owner = owner
dog = Dog(name='Fido', owner='Bob')
print dog.name
但是在这里,我有一只狗,但是腿和animal_type没有默认,事实上,它们根本没有设置(图片如下)。
这个例子可以制作一条有4条腿的狗,但我没有默认的能力,我必须给腿和类型,否则它不会创建:
class Animal(object):
def __init__(self, legs=4, animal_type='beast'):
self.legs = legs
self.animal_type = animal_type
class Dog(Animal):
def __init__(self, legs, animal_type, name=None, owner=None):
if legs:
self.legs = legs
if animal_type:
self.animal_type = animal_type
self.name = name
self.owner = owner
dog = Dog(4, 'dog', name='Fido', owner='Bob')
print dog.name
如果没有给出默认的父属性,我怎么能够子类化才能选择性地覆盖它们?所以我怎么能把这些类动物和狗,如果我不说腿或类型得到腿= 4的狗,和animal_type =野兽?谢谢
答案 0 :(得分:2)
class Animal(object):
def __init__(self, legs=4, animal_type='beast'):
self.legs = legs
self.animal_type = animal_type
class Dog(Animal):
def __init__(self, name=None, owner=None, **kwargs):
super(Dog, self).__init__(**kwargs)
self.name = name
self.owner = owner
dog = Dog(legs=4, animal_type='dog', name='Fido', owner='Bob')
在**kwargs
中捕获额外的参数,并用它们调用父的构造函数。