Calling base class method in Python

前端 未结 2 906
悲&欢浪女
悲&欢浪女 2020-12-13 09:13

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

相关标签:
2条回答
  • 2020-12-13 09:53

    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
    
    0 讨论(0)
  • 2020-12-13 09:57

    Two ways:

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

    0 讨论(0)
提交回复
热议问题