码迷,mamicode.com
首页 > 其他好文 > 详细

类的装饰器

时间:2018-10-21 12:14:50      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:none   type   成功   python   bar   item   module   obj   pass   

实现给类添加属性

def Typed(**kwargs):
    def deco(obj):
        for key,val in kwargs.items():
            # obj.key = val
            setattr(obj,key,val)
        return obj
    print(‘==>‘,kwargs)
    return deco

@Typed(x=1,y=2,z=3)
class Foo:
    pass

# f = Foo()
print(Foo.__dict__) #给Foo类添加属性成功
#{‘__module__‘: ‘__main__‘, ‘__dict__‘: <attribute ‘__dict__‘ of ‘Foo‘ objects>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘Foo‘ objects>, ‘__doc__‘: None, ‘x‘: 1, ‘y‘: 2, ‘z‘: 3}

@Typed(name=‘ago‘)
class Bar:
    pass

print(Bar.__dict__)
‘‘‘
==> {‘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}
==> {‘name‘: ‘ago‘}
{‘__module__‘: ‘__main__‘, ‘__dict__‘: <attribute ‘__dict__‘ of ‘Bar‘ objects>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘Bar‘ objects>, ‘__doc__‘: None, ‘name‘: ‘ago‘}
‘‘‘

类的装饰器

标签:none   type   成功   python   bar   item   module   obj   pass   

原文地址:https://www.cnblogs.com/chrrydot/p/9824400.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!