类的装饰器
Posted chrrydot
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了类的装饰器相关的知识,希望对你有一定的参考价值。
实现给类添加属性
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‘}
‘‘‘
以上是关于类的装饰器的主要内容,如果未能解决你的问题,请参考以下文章