Python。重写方法而不创建派生类并调用原始方法

标签 python

我有一个类似的函数:

ModuleA.py

Class FooClass:
    def fooMethod(self):
        self.doSomething()

现在我想重写该方法,但不从该类派生并从内部调用重写的方法:

ModuleB.py

from ModuleA import FooClass

def _newFooMethod(self):
    if(not hasAttr(self,"varA "):
        self.varA = 0
    #Do some checks with varA

    #CALL ORIGINAL fooMethod

FooClass.fooMethod = _newFooMethod

要知道的事情:

  • 我无权访问 FooClass。

  • 我无权访问 FooClass 的实例,因为它们很多而且不在一个地方。

  • 如您所见,我真正想要的是装饰 fooMethod。
  • 我还想创建一个像“varA”这样的变量以在 _newFooMethod 中使用它。我首先检查它是否已创建,如果没有则创建它,但我不知道这是否是最好的方法......

最佳答案

您不使用继承。你所做的就是所谓的猴子修补!

因此您可以执行以下操作:

ModuleB.py

from ModuleA import FooClass

# Preserve the original function:
FooClass.originalFooMethode = FooClass.fooMethode

def _newFooMethod(self):
    if(not hasAttr(self,"varA "):
        self.varA = 0
    #Do some checks with varA

    #CALL ORIGINAL fooMethod
    self.originalFooMethode()

FooClass.fooMethod = _newFooMethod

关于Python。重写方法而不创建派生类并调用原始方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41633831/

相关文章:

python - Patsy错误: Error evaluating factor: NameError:

python - 使用Python,如何查询json格式列中的元素并将它们变成行?

python - 神经网络Python错误 "Failed to get convolution algorithm"

python - Redis - 将 CSV 存储为值/blob?

python - 给定一系列 bin 概率,如何生成 bin 计数的随机样本?

python - 将训练数据的四分位数切割应用于测试数据

python - 根据另一个列表中的值从列表中过滤值的最有效方法是什么

Python:当旧对象与新对象相等时复制对象

python - Qml中的PyQt5 ApplicationWindow获取黑屏

python - 在 Python 中使用 Twitter Stream API