TypeError:非绑定方法fun1()必须以c1实例作为第一个参数调用(没有任何替代)

时间:2015-07-13 09:14:32

标签: python inheritance

在Python中,我正在实现继承。代码如下:

class c1(object):
    def __init__(self):
        pass
    def fun1(self):
        print 'In Fun1'

class c2(c1):
    def __init__(self):
       c1.__init__(self)
    def fun2(self):
       c1.fun1()
       print 'In Fun2'

obj = c2()
obj.fun2()


当我运行它时,我收到以下错误:

Traceback (most recent call last):
File "C:/Users/madhuras/Documents/inheritance_example.py", line 15, in <module>
obj.fun2()
File "C:/Users/madhuras/Documents/inheritance_example.py", line 11, in fun2
c1.fun1()
TypeError: unbound method fun1() must be called with c1 instance as first argument (got nothing instead)

为什么我收到此错误? 在此先感谢!

2 个答案:

答案 0 :(得分:0)

您无法使用fun1调用c1的方法c1.fun1(),因为它是一个实例方法(而不是类方法)。您可以使用super访问fun1()(甚至self.fun1())。与__init__()方法相同(虽然它目前正在运行),但最好也使用super()

尝试下面的内容 -

class c1(object):
    def __init__(self):
        pass
    def fun1(self):
        print 'In Fun1'

class c2(c1):
    def __init__(self):
       super(c2, self).__init__()
    def fun2(self):
       super(c2, self).fun1() #you can also do self.fun1() , but explicitly asking python to call super class's fun1 maybe better
       print 'In Fun2'

obj = c2()
obj.fun2()

答案 1 :(得分:0)

错误在fun2的定义中,您打算写

self.fun1()

或者,如果您想要指定实施,

c1.fun1(self)

而不是

c1.fun1()

c1是类的名称,而不是实例的名称。