Python学习过程中的问题:继承__init__的参数数量如何确定?

如题,版本python3.7,代码如下

class People():
    def __init__(self, name, city):
        self.name = name
        self.city = city
    def __str__(self):
        return "({} {})".format(self.name, self.city)
    def __repr__(self):
        return "({} {})".format(self.name, self.city)
    def moveto(self, new_city):
        self.city = new_city
    def __lt__(self, other):
        return self.city < other.city

class Teacher(People):
    def __init___(name, city, school):
        super().__init__(self, name, city)
        self.school = school
    def moveto(self, new_school):
        self.school = new_school
    def __lt__(self, other):
        return self.school < other.school


>>> Teacher("Xu", "China", "PekingUniversity")
Traceback (most recent call last):
  File "<pyshell#94>", line 1, in <module>
    Teacher("Xu", "China", "PekingUniversity")
TypeError: __init__() takes 3 positional arguments but 4 were given
>>> 

2个回答

给你检查了半天,才发现大兄弟你Teacher类里的__init__方法多打了一个下划线……所以变成了一个普通方法……相当于你子类没有定义构造函数,在实例化的时候就调用父类构造函数咯。
父类构造函数参数只有两个,你传三个参数当然会报错咯。

而且你的Teacher类狗杂函数缺少self

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐