我有一个类似的函数:
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/