【问题标题】:Calling base class method in Python在 Python 中调用基类方法
【发布时间】:2011-01-20 12:58:18
【问题描述】:

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

【问题讨论】:

    标签: python class


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      两种方式:

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

      【讨论】:

      • 第一种方式是通过x作为self参数吗?我不知道你能做到这一点......
      • @Wilduck。好问题,你知道那个问题的答案吗?
      • 是的,您将 x 作为 self 参数传递。当您在实例化对象上使用该方法时,例如x.print_it()x 会自动作为self 参数给出。当您使用类定义 (A.print_it) 中的原始函数时,A 不是 A 类型的实例化对象,因此它不会作为参数 A 给出并期望参数 self 的值.
      【解决方案3】:

      简单回答:

      super().print_it()
      

      【讨论】:

      • 在课堂内使用时可以使用,但问题显示了课堂外的用例。
      猜你喜欢
      • 2010-11-19
      • 1970-01-01
      • 2013-03-23
      • 2012-05-11
      • 2021-05-13
      • 2014-09-05
      • 2021-07-18
      • 2017-11-02
      • 2012-05-02
      相关资源
      最近更新 更多