【问题标题】:Python error with super [duplicate]超级Python错误[重复]
【发布时间】:2016-10-19 23:09:00
【问题描述】:

我正在尝试使用以下代码创建一个类人并将其继承给学生类。当我尝试运行时

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()

我假设它应该打印“Honor Student”,但是它会抛出一个 typeError 给我以下消息 TypeError: must be type, not classobj on super。我在这里做错了什么。我看到很少有类似问题的帖子,但无法处理我的问题。

【问题讨论】:

  • 你能发布实际的回溯吗?
  • Traceback (last last call last) 14 if self.scores > 90: 15 print('Honor Student') ---> 16 s = Student('Sam', 'Smith', 123456, 95) 17 s.calculate() in __init__(self, firstName, lastName, idNumber, scores) 9 class Student(Person): 10 def __init__(self, firstName, lastName, idNumber, scores): ---> 11 super( Student, self).__init__(firstName, lastName, idNumber) 12 self.scores = scores 13 def calculate(self): TypeError: must be type, not classobj

标签: python python-2.7 inheritance


【解决方案1】:

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 中,所有类都是新类型,因此不需要从对象显式继承。

【讨论】:

    猜你喜欢
    • 2014-10-18
    • 2016-10-30
    • 2013-09-01
    • 2016-10-19
    • 1970-01-01
    • 2016-09-03
    • 2015-11-30
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多