开发者

Calling base class method in Python

开发者 https://www.devze.com 2023-02-05 23:23 出处:网络
I have two classes A and B and A is base class 开发者_如何学Goof B. I read that all methods in Python are virtual.

I have two classes A and B and A is base class 开发者_如何学Goof 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 ???


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


Two ways:


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


Simple answer:

super().print_it()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号