【发布时间】:2016-05-08 18:40:19
【问题描述】:
我使用的是 Python 3.5.1。
我写了一个库,在某些情况下(当文件直接运行时,即__name__ == '__main__')我想在其中一个类中装饰某些方法。它应该装饰所有可以创建的实例。我想以一种非侵入性的方式来做,即理想情况下,我的库中的类不需要任何特殊代码。
一段时间后,我设法实现了这样的东西,符合我的要求:
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 库中是否有任何东西可以使这样的代码变得不必要,它已经实现了我正在做的事情,但更好?
【问题讨论】:
-
这看起来类似于我所做的here。我也想不出更简单的东西。
标签: python monkeypatching