动态修改类的属性
from __future__ import nested_scopes
import new
def enhance_method(klass, method_name, replacement):
'替换方法的函数'
method = getattr(klass, method_name)
setattr(klass, method_name, new.instancemethod(
lambda *args, **kwds: replacement(method, *args, **kwds), None, klass))
def method_logger(old_method, self, *args, **kwds):
'需要更的新方法',
做一些修改
somting.........
返回旧方法的返回值
return_value = old_method(self, *args, **kwds) # call the original method
return return_value
def demo():
class Deli:
def order_cheese(self, cheese_type):
print 'Sorry, we are completely out of %s' % cheese_type
d = Deli()
d.order_cheese('Gouda')
# 调用函数更新方法
enhance_method(Deli, 'order_cheese', method_logger)
d.order_cheese('Cheddar')
当需要修改第三方python包的某个类的某个方法时,这种修改方式非常有用