python动态修改类方法的执行逻辑,python动态逻辑,下面的代码演示如何给已经
python动态修改类方法的执行逻辑,python动态逻辑,下面的代码演示如何给已经
下面的代码演示如何给已经定义好的python类添加方法,替代已有方法:
from __future__ import nested_scopesimport newdef 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): '给方法添加调用执行日志' print '*** calling: %s%s, kwds=%s' % (old_method.__name__, args, kwds) return_value = old_method(self, *args, **kwds) # call the original method print '*** %s returns: %s' % (old_method.__name__, `return_value`) return return_valuedef 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包的某个类的某个方法时,这种修改方式非常有用。
相关内容
- 获取文件夹大小的python代码,获取python代码,import osfr
- easy_install 指定版本安装包,easy_install安装包,easy_insta
- python beautifulsoup分析网页示例,,beautifulsoa
- python破解验证码,python验证码,有开源的tesserac
- python easy_install 发生Unable to find vcvarsall.bat错误的处理方
- python错误处理记录完整的异常堆栈信息,python错误堆栈
- python使用深拷贝和浅拷贝复制对象,python拷贝,使用co
- easy_install 升级包,easy_install,easy_install
- easy_install 的n种用法,easy_install用法,easy_install
- python连接redis,pythonredis,首先需要通过easy_i
评论关闭