• 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}

    `

  • 相关阅读:
    [转]:Android 5.0的调度作业JobScheduler
    Android 移动端数据结构
    算法-二分查找
    设计模式-设计原则
    设计模式-单例模式(Singleton Pattren)(饿汉模式和懒汉模式)
    Android 7.0 Dialog 无法显示的问题
    设计模式-装饰模式(Decorator Pattern)
    产品中心2
    java中static和final修饰符
    java访问修饰符
  • 原文地址:https://www.cnblogs.com/python1988/p/11569029.html
Copyright © 2020-2023  润新知