如何在python中覆盖父类的函数? [英] How do I override a parent class's functions in python?

查看:355
本文介绍了如何在python中覆盖父类的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在子类中覆盖的父类中有一个私有方法 def __pickSide(self):。但是,子类仍然调用继承的 def __pickSide(self):。我该如何覆盖这个功能?子类的函数名称与父函数名称完全相同。

I have a private method def __pickSide(self): in a parent class that I would like to override in the child class. However, the child class still calls the inherited def __pickSide(self):. How can I override the function? The child class's function name is exactly the same as the parent's function name.

推荐答案

让我们看一下最简单的例子:

Let's look at the easiest example:

from dis import dis

class A(object):
  def __pick(self):
      print "1"

  def doitinA(self):
      self.__pick()

class B(A):
  def __pick(self):
      print "2"

  def doitinB(self):
      self.__pick()

b = B()
b.doitinA() # prints 1
b.doitinB() # prints 2

dis(A.doitinA)
print
dis(B.doitinB)

反汇编如下:

  8           0 LOAD_FAST                0 (self)
              3 LOAD_ATTR                0 (_A__pick)
              6 CALL_FUNCTION            0
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

 15           0 LOAD_FAST                0 (self)
              3 LOAD_ATTR                0 (_B__pick)
              6 CALL_FUNCTION            0
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

正如您所看到的,Python破坏了以两个下划线(以及对这些名称的访问!!)开头的函数名称包括类名 - 在这种情况下 _A__pick _B__pick )。这意味着定义函数的类确定调用哪个 __ pick 方法。

As you can see, Python mangles function names that begin with two underscores (and accesses to such names!!) to a name that includes the class name - in this case _A__pick and _B__pick). That means that the class in which a function is defined determines which of the __pick methods is called.

解决方案很简单,通过删除双下划线来避免伪私有方法。例如,使用 _pick 而不是 __ pick

The solution is simple, avoid pseudo-private methods by removing the double underscores. For example, use _pick instead of __pick.

这篇关于如何在python中覆盖父类的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆