Python类__init__覆盖,TypeError:__ init __()需要5个位置参数,但给出了6个

时间:2017-12-03 12:06:50

标签: python python-3.x

我正在学习python几天,我正在尝试为现有的类创建一个子类,但我找不到错误。我尝试了一切,但我认为我只是盲目......

输出总是会出现这样的错误

dog = Dog('Max', 120, 50, 'Woff', 'Tom')
TypeError: __init__() takes 5 positional arguments but 6 were given

这是代码,Garfield cat的动物部分工作正常。

class Dog(Animal):
    __owner = ""

    def __init(self, name, height, weight, sound, owner):
        self.__owner = owner
        super(Dog, self).__init__(name, height, weight, sound)

dog = Dog('Max', 120, 50, 'Woff', 'Tom') #<==== HERE ERROR OCCURES

2 个答案:

答案 0 :(得分:2)

Dog中的方法 init 也应该与__结尾:

class Dog(Animal):
    __owner = ""

# here
def __init__(self, name, height, weight, sound, owner):
    self.__owner = owner
    super(Dog, self).__init__(name, height, weight, sound)

答案 1 :(得分:0)

您的dog类的init方法名称错误,因此它不会覆盖基类init,它接受5个参数。

def __init(self, name, height, weight, sound, owner):
    self.__owner = owner
    super(Dog, self).__init__(name, height, weight, sound)

您在功能结束时缺少__。它应该是def __init__(..)