Calling base class method in Python

2019-03-09 04:44发布

I have two classes A and B and A is base class of B.

I read that all methods in Python are virtual.

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 ???

标签: python class
2条回答
Root(大扎)
2楼-- · 2019-03-09 05:06

Two ways:


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

查看更多
狗以群分
3楼-- · 2019-03-09 05:27

Using 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
查看更多
登录 后发表回答