python 猴子补丁一个新的 class 并导入它

python monkey patch a new class and import it

我想猴子修补一个新的 class 然后导入那个 class 但我收到错误 ModuleNotFoundError。同时我可以使用新的补丁功能。我相信我想念如何将它添加到“init”文件中。

请参阅以下简化示例:

import numpy
class wrong_functions():
    def wrong_add(num1, num2):
        return num1 + num2 + 1

numpy.random.wrong_functions = wrong_functions
numpy.random.wrong_functions.wrong_add(1,1) # works
from numpy.random.wrong_functions import wrong_add # does not work
from numpy.random.wrong_functions import * # does not work

你怎么看?这可能吗?

这是因为 import system.

通读文档,你可以找到这一段:

[...] the statement from spam.ham import eggs, sausage as saus results in

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage

问题是:__import__() 是做什么的?

The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope. [...]

A direct call to __import__() performs only the module search and, if found, the module creation operation.

因此,当您重新导入模块时,您的自定义设置将会丢失。

为确保它保持打开状态,您可以 import numpy as np 然后,在使用 np 时 - 在您评估这个新的 class 之后 - 您可以随时访问 wrong_add

>>> import numpy as np
>>> np.random.wrong_functions = wrong_functions
>>> np.random.wrong_function.wrong_add(1, 1)
3

编辑:如果你need/want只是调用wrong_add而不是函数的完整包路径,你总是可以将它分配给一个变量。

>>> wrong_add = np.random.wrong_function.wrong_add
>>> wrong_add(2, 2)
5