首页 > 其他 > 详细

类的装饰器

时间:2020-03-13 22:41:17      阅读:73      评论:0      收藏:0      [点我收藏+]
 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}

 

类的装饰器

原文:https://www.cnblogs.com/ch2020/p/12489279.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!