首页 > 其他 > 详细

类的装饰器

时间:2018-10-21 11:53:35      阅读:127      评论:0      收藏:0      [点我收藏+]

实现给类添加属性

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‘}
‘‘‘

类的装饰器

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

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