我有一个像这样的功能:
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 - python 。覆盖方法而不创建派生类并调用原始方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41633831/