【问题标题】:How to monkey patch an instance method of an external library that uses other instance methods internally?如何猴子修补内部使用其他实例方法的外部库的实例方法?
【发布时间】:2020-07-17 13:38:02
【问题描述】:

我需要修补我正在使用的库的实例方法中的逻辑。 为简洁起见,示例代码。 process 方法按原样使用Client 库的connect 方法,但我想修改它以使用不同的逻辑而不是 parsing_logic_1。做到这一点的最佳方法是什么?如果我在Usage 类中添加新的_patched_connect 方法,如何访问像url 这样的类变量?

class Client:
    def __init__(self, url)
        self.url = url
    def connect (self):
        if self.url == 'a':
         self._parsing_logic_1()
        if self.url == 'b':
         self._parsing_logic_2()
         else:
            pass
    def _parsing_logic_1(self):
        pass
    def _parsing_logic_2(self):
        pass
    def send(self):
        pass

# ----separate file --------

 class Usage:
    def __init__(self, client: Client):
        self.client = client
    
    def process(input):
        self.client.connect() # the connect method should use a different parsing logic for one case
        self.client.send()

【问题讨论】:

    标签: python python-decorators monkeypatching


    【解决方案1】:

    您需要导入您的类,然后将方法替换为修改后的方法。 在 python 中,您可以根据需要动态替换方法。

    例子:

    from x.y.z import Client
    
    def mynewconnect(self):
        # your code here
        self.url = "..."
        pass
    Client.connect = mynewconnect
    

    【讨论】:

    • mynewconnect() 方法中的self 是什么?它是该客户端类的实例吗?我不需要明确传递吗?
    • @sparkstar 每当您调用实例的方法时,该实例会自动作为第一个参数传递,您无需执行任何操作。这里有更多信息:programiz.com/article/python-self-why
    • self 只是一个约定,而不是关键字:您可以在方法中使用任何您想要的名称。您只需要知道,正如您和@CrazyChucky 所写,方法中接收的第一个参数是客户端类的实例。
    猜你喜欢
    • 2015-03-23
    • 1970-01-01
    • 2022-11-24
    • 2015-11-10
    • 2010-10-01
    • 1970-01-01
    • 2014-05-29
    • 2016-07-24
    • 1970-01-01
    相关资源
    最近更新 更多