我在使用此代码时遇到此问题,我不确定为什么我仍然会在此处获得此类型错误。我有以下Animal类,它是下面定义的Dog类的基类。我想创建一个继承自这个Animal类的Dog对象。
这是动物类:
class Animal(object):
__name = None
__height = None
__weight = None
__sound = None
def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
def set_name(self, name):
self.__name = name
def set_height(self, height):
self.__height = height
def set_weight(self, height):
self.__height = height
def set_sound(self, sound):
self.__sound = sound
def get_name(self):
return self.__name
def get_height(self):
return str(self.__height)
def get_weight(self):
return str(self.__weight)
def get_sound(self):
return self.__sound
def get_type(self):
print("Animal")
def toString(self):
return "{} is {} cm tall and {} kilograms and says {}".format(self.__name, self.__height, self.__weight, self.__sound)
然后我有以下Dog类继承自上面的Animal类:
class Dog(Animal):
__owner = None
def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
super(Dog, self).__init__(self, name, height, weight, sound)
def set_owner(self, owner):
self.__owner = owner
def get_owner(self):
return self.__owner
def get_type(self):
print("Dog")
def toString(self):
return "{} is {} cm tall and {} kilograms and says {}. His owner is {}".format(self.__name, self.__height, self.__weight, self.__sound, self.__owner)
当我尝试使用以下代码创建Dog对象时:
spot = Dog('Spot', 22, 11, 'Bark', 'John')
我得到以下TypeError:
TypeError: __init__() takes exactly 5 arguments (6 given)
有谁知道我为什么会收到此错误?我真的不明白这里发生了什么。
提前致谢!
编辑:从超类中取出self
后,当我尝试以下代码时,我现在收到AttributeError: 'Dog' object has no attribute '_Dog__name'
:
print(spot.toString())
答案 0 :(得分:2)
问题存在于超类的__init__
方法中。 super()
调用隐式传递self
作为第一个参数。只需使用:
def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
super(Dog, self).__init__(name, height, weight, sound)
仅当您通过名称引用超类时才需要显式自我。
def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
Animal.__init__(self, name, height, weight, sound)