python动态修改类方法

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):
    '给方法添加调用执行日志'
    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_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')

 

 

转载于:https://www.cnblogs.com/maple42/p/4065279.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值