【问题标题】:Error calling super __init__ in Python在 Python 中调用 super __init__ 时出错
【发布时间】:2015-12-09 02:28:38
【问题描述】:

我无法调用超级 init 方法,我对 python 很陌生。代码:

class Employee:
    "Our common employee base class"

    empCount = 0

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1

    def displayCount(self):
        print "Total number of employees: ", Employee.empCount

    def displayEmployee(self):
        print "Name: %s , Salary: $%d" % (self.name,self.salary)

    def __del__(self):
        print "Class destroyed"

现在我也有一个班级SuperIntern:

class SuperIntern(Employee):
    internCount = 0

    def __init__(self, name, salary):
        super(self.__class__, self).__init__(name, salary)
        SuperIntern.internCount +=1

    def displayNumInterns(self):
        print "We have %d interns" %SuperIntern.internCount


intern2 = SuperIntern("Harry", 22)

当我尝试创建此类的实例时,我收到错误:super(self.class, self).init(name, Salary), TypeError:必须是类型,而不是 classobj。我试过直接使用类名 SuperIntern 而不是 self.class ,它仍然会引发错误。有人可以指出我正确的方向吗?谢谢!

【问题讨论】:

  • 顺便说一句,不要使用super(self.__class__, self)。如果您的继承树的深度超过两个类,它将中断。您必须实际命名定义该方法的类,即super(SuperIntern, self)

标签: python


【解决方案1】:

在 Python 2 中,super 只能用于新型类。 Employee 必须扩展 object:

class Employee(object):
    # ...

这使得Employee 成为一个新型类(SuperIntern 也是如此,因为它现在扩展了一个新型类)。

【讨论】:

  • 谢谢。现在工作。
猜你喜欢
  • 1970-01-01
  • 2017-02-23
  • 2017-06-30
  • 2020-05-17
  • 2021-03-23
  • 2020-11-06
  • 1970-01-01
  • 2020-07-06
  • 2020-03-13
相关资源
最近更新 更多