在Python中调用基类方法

时间:2011-01-20 12:58:18

标签: python class

我有两个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 ???

2 个答案:

答案 0 :(得分:39)

使用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

答案 1 :(得分:26)

两种方式:


>>> A.print_it(x)
'A'
>>> super(B, x).print_it()
'A'