zoukankan      html  css  js  c++  java
  • 类的装饰器

     1 def demo(obj):
     2     print('===================')
     3     obj.x = 1
     4     obj.y = 2
     5     obj.z = 3
     6     return obj
     7 
     8 @demo
     9 class Foo:
    10     pass
    11 
    12 f1 = Foo()
    13 print(Foo.__dict__)
    14 输出:
    15 ===================
    16 {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'x': 1, 'y': 2, 'z': 3}

    一切皆对象,函数和类都是对象    例如:

     1 def demo(obj):
     2     print('===================')
     3     obj.x = 1
     4     obj.y = 2
     5     obj.z = 3
     6     return obj
     7 @demo
     8 def test():
     9     print('这是个测试函数')
    10 test()
    11 print(test.__dict__)
    12 输出:
    13 ===================
    14 这是个测试函数
    15 {'x': 1, 'y': 2, 'z': 3}
     1 def test(**kwargs):
     2     def wrapper(obj):
     3         for key, val in kwargs.items():
     4             setattr(obj, key, val)
     5         return obj
     6 
     7     return wrapper
     8 
     9 
    10 @test(a=1, b=2)  # @wrapper
    11 class Foo:
    12     def __init__(self, name):
    13         self.name = name
    14 
    15 
    16 print(Foo.__dict__)
    17 输出:
    18 {'__module__': '__main__', '__init__': <function Foo.__init__ at 0x00000000024C3280>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'a': 1, 'b': 2}
  • 相关阅读:
    别了,DjVu!
    DjVu转PDF
    我的电子书历程
    连续翻页浏览器面临的共同问题
    对超过2TB的硬盘进行分区需要使用parted
    DB2常用命令
    CentOS增加网卡
    mysql相关参数解读
    max_user_connections参数设置试验
    mysql最大连接数试验
  • 原文地址:https://www.cnblogs.com/ch2020/p/12489279.html
Copyright © 2011-2022 走看看