zoukankan      html  css  js  c++  java
  • 2019年9月22日 类的装饰器

    装饰器本身就是函数 

    回顾:

    def deco(func):
        print('>>deco>>')
        return func
    
    @deco # 做了 这么一件事情:test=deco(test)
    def test():
        print('testing')
    
    test()

    》》》》》》

    >>deco>>
    testing

    def deco(obj):
        print('>>deco>>',obj)
        obj.x=1
        obj.y=2
        obj.z=3
        return obj
    
    @deco #Foo=deco(Foo)
    class Foo:
        pass
    
    f1=Foo()
    print(Foo.__dict__)

    >>>>>>

    >>deco>> <class '__main__.Foo'>
    {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'x': 1, 'y': 2, 'z': 3}

    def deco(obj):
        print('>>deco>>',obj)
        obj.x=1
        obj.y=2
        obj.z=3
        return obj
    
    
    @deco
    def test():#验证一切皆对象
        print('testing')
    print(test.__dict__)

    》》》》

    >>deco>> <function test at 0x10203d048>
    {'x': 1, 'y': 2, 'z': 3}

    def Typed(**kwargs):#通过函数的嵌套,达到加参数的目的
        def deco(obj):
            print('>>deco>>',obj)
            print('deco',kwargs)
            for key,val in kwargs.items():
                # obj.__dict__[key]=val#这个方法不知道为啥不行
                setattr(obj,key,val)
            return obj
        print('>>>',kwargs)#先执行这一步
        return deco#再执行这一步
    
    
    @Typed(x=1,y=2,z=3)#先运行Typed函数
    class Foo:
        pass
    
    print(Foo.__dict__)

    >>>>>

    >>> {'x': 1, 'y': 2, 'z': 3}
    >>deco>> <class '__main__.Foo'>
    deco {'x': 1, 'y': 2, 'z': 3}
    {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'x': 1, 'y': 2, 'z': 3}

    `

  • 相关阅读:
    转 UICollectionView 详解
    springboot配置ssl证书
    服务器ganglia安装(带有登录验证)
    eureka配置说明
    Servlet中获取请求参数问题
    apidoc学习(接口文档定义取代word)
    markdown语法
    JVM分析
    ftp上传或下载文件工具类
    ubuntu命令安装
  • 原文地址:https://www.cnblogs.com/python1988/p/11569029.html
Copyright © 2011-2022 走看看