Python 2.7 __init__() 需要2个参数(给了3个)

1 投票
2 回答
2582 浏览
提问于 2025-04-28 06:01

我有这些类。Person是父类,而Student是子类:

class Person(object):
    def __init__(self, name):
        self.name = name

class Student(Person):
    def __init__(self, avr, name):
        self.avr = avr
        super(Student, self).__init__(self, name)

当我尝试创建一个Student的实例时,出现了这个错误:

__init__() takes exactly 2 arguments (3 given)

我的代码哪里出问题了?

暂无标签

2 个回答

-1

你可以使用

super(Student, self).__init__(name)

在这里,self已经被传递给init方法,所以你在__init__方法里不需要再写一次。

但是如果你使用

super(Student, Student).__init__(self, name)

或者

super(Student, self.__class__).__init__(self, name)

你就必须在__init__方法里写上self。

5

如果你在使用super这个东西,你就不需要把self这个参数传给目标方法。这个参数会自动传递。

super(Student, self).__init__(name)

这样一来,总共有两个参数(self和name)。而当你把self传过去的时候,就变成了三个参数(self、self和name)。

撰写回答