我在调用超级 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 ,它仍然会抛出错误。有人能指出我正确的方向吗?谢谢!
答案 0 :(得分:1)
在Python 2中,super
只能用于新式类。 Employee
必须延长object
:
class Employee(object):
# ...
这使得Employee
成为一种新式的类(以及SuperIntern
,因为它现在扩展了一种新式的类。)