gpt4 book ai didi

python - 猴子从库中修补 python 类方法

转载 作者:行者123 更新时间:2023-12-04 08:51:40 27 4
gpt4 key购买 nike

我正在导入其他人制作的库,并且我想更改该库中特定类方法的工作方式,因此我已将该类方法复制到我自己的文件中,并希望在运行时替换它。这对于函数似乎工作得很好,但对于类方法似乎分崩离析。a.library.package.library_file.py

class LibraryClass(ParentClass):
@classmethod
def get_cost(cls, time):
return int(time * cls.hourly)
我想用这个替换它
class LibraryClass(ParentClass):
@classmethod
def get_cost(cls, time):
return 1234
我试图做一个正常的替换,它对常规功能很好
import a.library.package.library_file

...

a.library.package.library_file.LibraryClass.get_cost = get_cost
但它似乎根本无法正常工作,在错误的时间使用错误的参数调用该方法并导致崩溃。在对 Google、StackOverflow 和 Python 进行了一些研究之后,我开始尝试使用模拟类。
from unittest.mock import patch

@patch.object('a.library.package.library_file.LibraryClass', 'get_cost')
def get_cost(cls, time):
return 1234
好消息是它没有崩溃,坏消息是它什么也没做,旧代码仍然存在,就像我的代码不存在一样。
我已经尝试了各种其他方法来做到这一点,例如
import a.library.package.library_file

@patch.object(a.library.package.library_file.LibraryClass, 'get_cost')
...
或者
from a.library.package.library_file import LibraryClass

@patch.object(LibraryClass, 'get_cost')
...
但每次都没有碰过这个方法。好像我的代码不存在,使用的是旧代码。

最佳答案

事实证明,解决方案很简单,正如我想象的那样。花了一天多的时间挖掘,网上任何地方都没有帮助,但我在谷歌的第 2 页上发现了一个来自中国的晦涩随机帖子,最终回答了我的问题。 Link Here
这是有效的结果代码

from types import MethodType
from a.library.package.library_file.py import LibraryClass

def get_cost(cls, time):
return 1234


LibraryClass.get_cost = MethodType(get_cost, LibraryClass)
这与替换函数相同,只是您需要将其包装在“MethodType”中,因为您换出的代码与该类具有“classmethod”关联,因此新代码需要相同才能工作。

关于python - 猴子从库中修补 python 类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64069375/

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