在Python中调用super __init__时出错

时间:2015-09-12 17:50:08

标签: python

我在调用超级 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 ,它仍然会抛出错误。有人能指出我正确的方向吗?谢谢!

1 个答案:

答案 0 :(得分:1)

在Python 2中,super只能用于新式类。 Employee必须延长object

class Employee(object):
    # ...

这使得Employee成为一种新式的类(以及SuperIntern,因为它现在扩展了一种新式的类。)