简体   繁体   English

覆盖(monkeypatch)第三方模块中的功能,该功能由该第三方模块中的其他功能使用

[英]override (monkeypatch) a function in a 3rd party module used by other functions in that 3rd party module

I want to override a function internal to some 3rd party code. 我想覆盖一些第三方代码内部的函数。 Here's an example of my intent. 这是我意图的一个例子。

(edit: I've corrected the spelling error below, and now this does work as intended) (编辑:我已经纠正了下面的拼写错误,现在确实可以正常工作了)

#--- dog.py (3rd party code) ---
def _bark():
    print("WOOF!")

def make_it_bark():
    _bark()

#--- make_catlike.py (my code)---
import dog
dog._bark = lambda: print("MEOW") #<<-- 'bark' in original, so failed!!!!
dog.make_it_bark()
# edit: now prints out "MEOW" instead of "WOOF!" like I want

How do I get the 3rd party dog.py code to use my version of _bark? 如何获得第三方dog.py代码以使用的_bark版本?

[conclusion: This was only failing because of a spelling error . [结论:这只是因为拼写错误而失败。 Thanks for the help!!] 谢谢您的帮助!!]

You have a simple typo in make_catlike.py --- you're missing the leading underscore. 您在make_catlike.py有一个简单的错字---您缺少前划线。 The whole file should read: 整个文件应为:

#--- make_catlike.py (my code)---
import dog
dog._bark = lambda: print("MEOW")
#   ^-------- Underscore was missing.
dog.make_it_bark()  # Prints "MEOW".

Note that, in more complex cases, other kinds of things could go wrong... 请注意,在更复杂的情况下,其他类型的事情也可能出错。

For instance, if the behavior you want to change happens when the module is imported, altering that module's code after import dog returns won't help. 例如,如果要更改的行为发生在导入模块时,则 import dog返回更改该模块的代码将无济于事。

In code you provided make sure you have not forgotten underscore when redefining _bark function. 在提供的代码中,请确保在重新定义_bark函数时没有忘记下划线。 If you want to change method of a class, a good idea would be to inherit that class and override method in your class. 如果要更改类的方法,一个好主意是继承该类并在您的类中重写方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM