gpt4 book ai didi

Python。在不创建派生类的情况下重写方法并调用原始方法

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:44 24 4
gpt4 key购买 nike

我有这样的功能:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com