简体   繁体   中英

Error calling super __init__ in Python

I am having trouble calling the super init method, I'm very new to python. Code:

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"

Now I also have a class 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)

When I try to create an instance of this class I get the error: super(self. class , self). init (name, salary), TypeError: must be type, not classobj. I have tried using the class name SuperIntern directly instead of self. class and it still throws an error. Could someone point me in the right direction please? Thanks!

In Python 2, super can only be used with new-style classes. Employee must extend object :

class Employee(object):
    # ...

This makes Employee a new-style class (and SuperIntern as well, since it now extends a new-style class).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM