我在Python 3.5.1上。 我寫了一個庫,並且在某些情況下(當文件直接運行時,即__name__ == '__main__'
),我想在某個類中修飾某些方法。它應該修飾所有可以創建的實例。我想以非侵入性的方式來完成,理想情況下,我的圖書館中的類不需要任何特殊的代碼。在Python中修補類的所有實例
一段時間後,我成功地實施這樣的事情,這符合我的要求:
def patch(clazz, name, replacement):
def wrap_original(orig):
# when called with the original function, a new function will be returned
# this new function, the wrapper, replaces the original function in the class
# and when called it will call the provided replacement function with the
# original function as first argument and the remaining arguments filled in by Python
def wrapper(*args, **kwargs):
return replacement(orig, *args, **kwargs)
return wrapper
orig = getattr(clazz, name)
setattr(clazz, name, wrap_original(orig))
def replacement_function(orig, self, ... other argumnents ...):
# orig here is the original function, so can be called like this:
# orig(self, ... args ...)
pass
patch(mylib.MyClass, 'method_name', replacemment_function)
令人驚訝的是,此代碼的工作,雖然我還沒有與類的方法測試過,但我不現在需要它。它還修補修補之前創建的實例,雖然我還不確定它是否良好; d
上面的代碼無疑是困難的,我需要一段時間來圍繞它的工作方式,它,以寫出解釋評論。我會喜歡更容易的事情。
問題:Python庫中是否有任何東西會使這樣的代碼變得不必要,這已經實現了我正在做的事情,但更好?
這看起來類似於我在[這裏](https://github.com/host-anshu/simpleInterceptor/blob/master/interceptor.py)所做的。我也無法想出更簡單的東西。 –