0
我有以下问题。我想装饰从模块导入的特定功能。像这样:如何装饰/覆盖与导入方式无关的功能?
import matplotlib.pyplot as plt
plt.figure = decorator(plt.figure)
然而,要做到这一点就这样,我需要知道用户是如何打算进口特定功能(在这个例子中matplotlib图形功能)。我正在寻找的是装饰功能的方式,与其如何导入无关:
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.pyplot import figure
decorate_figure_function() # This function shall decorate the figure-function independent of how it is imported
我希望你能理解我的问题。
语境:我想建立一个matplotlib记录仪,它可以监测数字
对象'图'总是会是相同的,不管它是如何进口的,不是吗?这应该是你装饰功能的参数。我在这里看不到问题。 – toine
这是同一个对象,是的。但是当我想要装饰它时,我必须将它分配给某些东西(比如在第一个例子中)。我不能修改对象本身,或者我可以吗? – arthaigo
你可能想尝试'mock.patch':(https://docs.python.org/dev/library/unittest.mock.html#unittest.mock.patch) – VPfB