我有两个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 ???
Run Code Online (Sandbox Code Playgroud)
use*_*312 40
使用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
Run Code Online (Sandbox Code Playgroud)
pri*_*oot 31
两种方式:
>>> A.print_it(x)
'A'
>>> super(B, x).print_it()
'A'