在Python中调用基类方法

use*_*312 40 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 ???
Run Code Online (Sandbox Code Playgroud)

use*_*312 40

使用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
Run Code Online (Sandbox Code Playgroud)


pri*_*oot 31

两种方式:


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

  • 传递`x`作为自我参数的第一种方式是什么?我不知道你能做到这一点...... (2认同)
  • 是的,您将 `x` 作为 self 参数传递。当你在一个实例化的对象上使用这个方法时,比如 `x.print_it()`,`x` 会自动作为 `self` 参数给出。当您使用类定义中的原始函数 (`A.print_it`) 时,`A` 不是类型为 `A` 的实例化对象,因此它不会作为参数 `A` 给出并期望参数 `A` 的值自`。 (2认同)