Python 2.7 __init__() takes exactly 2 arguments (3 given)

偶尔善良 提交于 2019-12-20 04:59:15

问题


I've got these classes. Person is the parent class and Student is the child class:

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)

I get this error when I try to make an instance of Student:

__init__() takes exactly 2 arguments (3 given)

What is wrong with my code?


回答1:


If you are using super, you don't pass self to the target method. It is passed implicitly.

super(Student, self).__init__(name)

That's 2 arguments total (self, name). When you passed self, that was 3 total (self, self, name).




回答2:


You can use

super(Student, self).__init__(name)

in which self has been passed to init method,so you don't need to write it out again in __init__ method. But if you use

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

or

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

you have to write down self in __init__ method.



来源:https://stackoverflow.com/questions/26437426/python-2-7-init-takes-exactly-2-arguments-3-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!