加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

类的装饰器

发布时间:2020-12-20 11:00:02 所属栏目:Python 来源:网络整理
导读:#装饰器回顾 ```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(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,z=3) #1.Typed(x=1,z=3) --->deco [email?protected]>Foo=deco(Foo)
class Foo:
pass
print(Foo.__dict__)
```

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读