所以有一個ClassInOtherCode在模塊othercode.py中呼叫的類,我不能改變。在othercode.py那里有一個被呼叫的函式otherfunc(),它有時會實體化ClassInOtherCode.
在我運行之前,otherfunc()有沒有辦法告訴 Python 通過一些引發的事件告訴我的代碼,或者在ClassInOtherCode實體化時呼叫我的一些代碼?
我指的不是我的代碼檢查是否ClassInOtherCode在呼叫 之后實體化otherfunc(),而是 Python 推送到我的代碼。通過推送,我指的是客戶端瀏覽器接收資訊而不是不斷請求資訊的 Web 模式。
我的代碼不是網路應用程式。我只是想做一個類比,所以我的問題希望更清楚。
uj5u.com熱心網友回復:
如果您無權訪問其源代碼以將所需的功能添加到其方法中,則可以使用猴子補丁 :ClassInOtherCode__init__
from othermodule import otherfunc, ClassInOtherCode
default_init = ClassInOtherCode.__init__
def my_init(*args, **kwargs):
print("ClassInOtherCode is instantiated!")
default_init(*args, **kwargs)
ClassInOtherCode.__init__ = my_init
result = otherfunc() # This should trigger your print statement
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/310925.html
標籤:Python
上一篇:如何將字串的格式決議為另一種格式
