在Python中调用基类方法 [英] Calling base class method in Python
本文介绍了在Python中调用基类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个类A和B,A是B的基类。
I have two classes A and B and A is base class of B.
我读到Python中的所有方法都是虚拟的。
I read that all methods in Python are virtual.
那么我如何调用基类的方法,因为当我尝试调用基类的方法时,派生类的方法被按预期方式调用了?
$ b
So how do I call a method of the base because when I try to call it, the method of the derived class is called as expected?
>>> 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 ???
推荐答案
使用超级:
>>> 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
这篇关于在Python中调用基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文