zoukankan      html  css  js  c++  java
  • 动态修改类的属性

    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包的某个类的某个方法时,这种修改方式非常有用

  • 相关阅读:
    2017 ICPC beijing E
    1629 B君的圆锥
    1298 圆与三角形
    通过String获取字符数组
    Java中的代码点与代码单元
    数据库事务隔离级别
    oracle修改密码、添加用户及授权
    Python起航
    软件测试常见概念
    TestNG--@Factory
  • 原文地址:https://www.cnblogs.com/alangwansui/p/3127168.html
Copyright © 2011-2022 走看看