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