【问题标题】:TypeError: unbound method __init__() must be called with payroll instance as first argument (got int instance instead)TypeError:未绑定的方法 __init__() 必须以工资单实例作为第一个参数调用(取而代之的是 int 实例)
【发布时间】:2015-07-10 08:50:52
【问题描述】:
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()

尝试使用“Super”,但遇到了同样的错误:

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 编写这段代码,那就太好了,这样我就可以理解它的实际功能了。

【问题讨论】:

    标签: python python-2.7 typeerror superclass


    【解决方案1】:

    你应该像这样使用类:

    class employee(Thread):
    

    而不是这个:

    class employee(object):
    

    【讨论】:

      【解决方案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
      

      【讨论】:

        猜你喜欢
        • 2015-11-07
        • 2017-05-10
        • 1970-01-01
        • 2014-12-10
        • 1970-01-01
        • 2018-05-10
        • 1970-01-01
        • 1970-01-01
        • 2017-04-03
        相关资源
        最近更新 更多