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}
  • 相关阅读:
    Leetcode 15. 3Sum
    本周学习小结(01/07
    面试总结之Data Science
    学习笔记之MongoDB
    本周学习小结(13/05
    Django知识点总结
    Django【进阶篇 】
    Django【基础篇】
    如何拿到半数面试公司Offer——我的Python求职之路(转载)
    Django框架(三)
  • 原文地址:https://www.cnblogs.com/ch2020/p/12489279.html
Copyright © 2011-2022 走看看