类的装饰器

实现给类添加属性

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

猜你喜欢

转载自www.cnblogs.com/chrrydot/p/9824400.html