• 动态修改类的属性


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

  • 相关阅读:
    从头学pytorch(二十一):全连接网络dense net
    Linux环境实现python远程可视编程
    centos7安装Anaconda3
    sql语句中包含引号处理方法
    syslog 日志
    python 判断是否为中文
    numpy简介
    django之模板显示静态文件
    Linux(Ubuntu)安装libpcap
    Bug预防体系
  • 原文地址:https://www.cnblogs.com/alangwansui/p/3127168.html
Copyright © 2020-2023  润新知