我正在尝试创建一个Class Person,并使用以下代码将其继承到Student类。当我尝试运行时
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')
而我这样做,
s = Student('Sam', 'Smith', 123456, 95)
s.calculate()
我认为应该打印“荣誉学生”#39;但它抛出一个typeError给我以下消息TypeError:必须是类型,而不是超级上的classobj。我在这做错了什么。我看到很少有类似问题的帖子,但无法在我的网站上工作。
答案 0 :(得分:2)
super
的使用仅适用于new-type classes。
您需要做的就是让Person
在类定义中继承object
。
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')
请注意,在Python 3中,所有类都是新类型,因此不需要显式继承来自对象。