在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)
为什么我收到此错误? 在此先感谢!
答案 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是类的名称,而不是实例的名称。