TypeError:unbound方法__init __()必须使用payroll实例作为第一个参数调用(改为使用int实例)

时间:2015-04-30 15:08:31

标签: python python-2.7 typeerror superclass

class employee(object):
    def __init__(self,employeenumber,name):
        self.employeenumber=employeenumber
        self.name=name
    def printdata(self):
        print self.employeenumber
        print self.name
class payroll(employee):
    def __init__(self,employeenumber,name,salary):
        employee. __init__(employeenumber,name)
        self.salary=salary
    def outdata(self):
        self.printdata()
        print self.salary
class leave(payroll):
    def __init__(self,employeenumber,name,salary,nodays):
        payroll. __init__(employeenumber,name,salary)
        self.nodays=nodays
    def showdata(self):
        self.outdata()
        print self.nodays

emp1=leave(3,"sam",5000,8)
emp1.showdata()

尝试使用“超级”,但得到了同样的错误:

Traceback (most recent call last):
  File "C:/Python27/limb.py", line 23, in <module>
    emp1=leave(3,"sam",5000,8)
  File "C:/Python27/limb.py", line 17, in __init__
    payroll. __init__(employeenumber,name,salary)
TypeError: unbound method __init__() must be called with payroll instance as first argument (got int instance instead)

如果有人建议用super编写这段代码以便我能理解它的实际功能,那就太好了。

2 个答案:

答案 0 :(得分:2)

要直接在类上调用重写的__init__方法,您需要明确传入self

class leave(payroll):
    def __init__(self, employeenumber, name, salary, nodays):
        payroll.__init__(self, employeenumber, name, salary)
        self.nodays=nodays

因为在类上查找的方法没有绑定到实例(因为Python在这种情况下无法知道实例是什么)。因此,您将employeenumber作为第一个参数传递,而不是用作该方法的self参数的有效对象类型。

或者,使用super() function生成绑定方法(因此self绑定到实例的方法对象):

class leave(payroll):
    def __init__(self, employeenumber, name, salary, nodays):
        super(leave, self).__init__(employeenumber, name, salary)
        self.nodays=nodays

答案 1 :(得分:0)

您应该使用这样的类:

class employee(Thread):

代替此:

class employee(object):