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')

 

 

相关文章:

  • 2021-08-28
  • 2022-03-09
  • 2022-12-23
  • 2021-12-21
  • 2022-12-23
  • 2022-12-23
  • 2022-02-13
  • 2023-03-20
猜你喜欢
  • 2021-07-12
  • 2022-01-23
  • 2021-10-07
  • 2021-10-07
  • 2021-11-26
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案