类的装饰器

#装饰器回顾
```python
def deco(func):
print('==========')
return func

@deco #test=deco(test)
def test():
print('test函数运行')
test()


#现在把test改成一个类
@deco #Foo=deco(Foo)
class Foo:
print('test函数运行')
f1=Foo()
```
装饰器装饰实例与装饰类,本质效果是一样的
即一切皆对象

#利用装饰器给类加参数,返回新类
```python
def deco(obj):
print('==========',obj)
obj.x=1
obj.y=2
obj.z=3
return obj
@deco #Foo=deco(Foo)
class Foo:
pass

print(Foo.__dict__)

#“@”这个语法糖 把一切传过来的都当做对象处理
#一切皆对象
#@deco #test=deco(test)
def test():
print('test函数')
# test.x=1
# test.y=1
print(test.__dict__)
```

#类的装饰器修订版
```python
def Typed(**kwargs):
def deco(obj):
for key,val in kwargs.items():
# obj.key=val 这样不行,会给字典加个 叫“key”的属性
setattr(obj,key,val)
return obj
return deco

#Typed(x=1,y=2,z=3)先执行,获得deco,且这几个参数已#经传进去了,现在需要把传进去的值,设置到字典中
#变成@deco,本质是Foo=deco(Foo)
#deco外面套一层,是因为deco传入的是obj ,如果想在同#时或在此之前就把kwargs 也就是想设定的值传给deco,
#可以在外面套一层,等运行到deco时候,kward已经在他
#的上层作用域中

@Typed(x=1,y=2,z=3) #1.Typed(x=1,y=2,z=3) --->deco 2.@deco---->Foo=deco(Foo)
class Foo:
pass
print(Foo.__dict__)
```

#类的装饰器的运用
详见 描述符优先级和运用

 

posted @ 2019-08-14 18:43  坚持fighting  阅读(494)  评论(0编辑  收藏  举报