zoukankan      html  css  js  c++  java
  • 如何写活类的装饰器

    def teyed(**kwargs):
      def demo(obj):
        print('======',kwargs)
        return obj
      print('---->',kwargs)
      return demo  #不能加括好
    
    @teyed(x=1,y=2,w=3)   
    class Foo():
      print('***')
      pass
    
    @teyed(f=3,g=23)
    class Bar():
      print('Bar***')
      pass
    
    
    
    '''打印部分
    D:Python34python.exe
    
    ----> {'w': 3, 'y': 2, 'x': 1}
    ***
    ====== {'w': 3, 'y': 2, 'x': 1}
    ----> {'f': 3, 'g': 23}
    Bar***
    ====== {'f': 3, 'g': 23}
    
    
    Process finished with exit code 0
    '''
    

     

    def teyed(**kwargs):
      def demo(obj):
        for key,val in kwargs.items():
          setattr(obj,key,val)
        return obj
      return demo  #不能加括好
    
    @teyed(x=1,y=2,w=3)
    class Foo():
      pass
    print(Foo.__dict__)
    
    @teyed(f=3,g=23)
    class Bar():
      pass
    print(Bar.__dict__)
    
    
    '''打印部分
    {'__doc__': None, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Foo' objects>, 'x': 1, 'w': 3, 'y': 2}
    
    {'f': 3, '__doc__': None, '__weakref__': <attribute '__weakref__' of 'Bar' objects>, '__module__': '__main__', 'g': 23, '__dict__': <attribute '__dict__' of 'Bar' objects>}
    
    '''
    

      

     

  • 相关阅读:
    c博客作业05--指针
    C博客作业04--数组
    C博客作业03--函数
    C博客作业02--循环结构
    C博客作业01--分支、顺序结构
    我的第一篇博客
    DS博客作业05--查找
    DS博客作业04--图
    DS博客作业03--树
    DS博客作业02--栈和队列
  • 原文地址:https://www.cnblogs.com/heluobing/p/10817525.html
Copyright © 2011-2022 走看看