Python error with super
本问题已经有最佳答案,请猛点这里访问。
我试图创建一个类人,并用以下代码将其继承给类学生。当我试图跑步时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Person: def __init__(self, firstName, lastName, idNumber): self.firstName = firstName self.lastName = lastName self.idNumber = idNumber def printPerson(self): print"Name:", self.lastName +",", self.firstName print"ID:", self.idNumber class Student(Person): def __init__(self, firstName, lastName, idNumber, scores): super(Student, self).__init__(firstName, lastName, idNumber) self.scores = scores def calculate(self): if self.scores > 90: print('Honor Student') |
我知道,
1 2 | s = Student('Sam', 'Smith', 123456, 95) s.calculate() |
我假设它应该打印"荣誉学生",但它抛出了一个类型错误,给了我以下消息typeerror:必须是类型,而不是super上的classobj。我在这里做错什么了。我很少看到有类似问题的帖子,但我不能继续写我的。
您需要做的只是在类定义中让
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Person(object): def __init__(self, firstName, lastName, idNumber): self.firstName = firstName self.lastName = lastName self.idNumber = idNumber def printPerson(self): print"Name:", self.lastName +",", self.firstName print"ID:", self.idNumber class Student(Person): def __init__(self, firstName, lastName, idNumber, scores): super(Student, self).__init__(firstName, lastName, idNumber) self.scores = scores def calculate(self): if self.scores > 90: print('Honor Student') |
请注意,在Python3中,所有类都是新类型的,因此不需要从对象显式继承。