在Python中调用基类方法
我有两个类,A和B,A是B的父类。
我听说在Python中,所有的方法都是虚拟的。
那么我该怎么调用父类的方法呢?因为当我尝试调用时,总是会调用子类的方法,这是我预期的结果。
>>> class A(object):
def print_it(self):
print 'A'
>>> class B(A):
def print_it(self):
print 'B'
>>> x = B()
>>> x.print_it()
B
>>> x.A ???
3 个回答
0
简单的回答:
super().print_it()
40
有两种方法:
>>> A.print_it(x)
'A'
>>> super(B, x).print_it()
'A'
59
使用 super:
>>> class A(object):
... def print_it(self):
... print 'A'
...
>>> class B(A):
... def print_it(self):
... print 'B'
...
>>> x = B()
>>> x.print_it() # calls derived class method as expected
B
>>> super(B, x).print_it() # calls base class method
A