python 装饰器
来源:互联网 发布:中国cpi数据分析 编辑:程序博客网 时间:2024/06/01 19:36
Python装饰器
如果要增强某一函数的功能,但又不希望修改原函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。写代码需要遵循开放封闭原则,已经实现的功能代码不允许被修改,但可以被扩展。
例如要给func函数增加一功能,只需定义一个login装饰器即可
deflogin(func):
definner(arg,arg1):
print('login')
returnfunc(arg,arg1)
returninner
@login #此次相当于执行了func=login(func)
def func(arg,arg1):
print('func: %s -- %s'%(arg,arg1))
func('hello','world')
运行结果:
login
func: hello -- world
如果decorator本身需要传入参数,那就需要编写一个返回decorator的高阶函数
def login(txt):
defouter(func):
definner(arg,arg1):
print(txt)
returnfunc(arg,arg1)
returninner
returnouter
@login('hehe') #装饰器带参数
#第一步执行login('hehe')
#第二步执行@outer(func)
def func(arg,arg1):
print('func: %s -- %s'%(arg,arg1))
func('hello','world')
运行结果:
hehe
func: hello -- world
- python装饰器装饰类
- [python]python装饰器
- Python装饰器学习
- Python装饰器
- python 装饰器
- Python装饰器
- python 装饰器 应用
- python 装饰器2
- Python装饰器学习
- python装饰器
- python装饰器
- python 装饰器入门
- python装饰器
- python装饰器
- python 装饰器'@'
- python装饰器
- Python装饰器详解
- python 装饰器
- react-native navigation的学习与使用
- Android常用控件
- 数据库锁表及阻塞的原因和解决办法
- Redis 的五中数据类型
- MVC初体验
- python 装饰器
- 英语思维框架整理
- web服务器apache架构与原理
- 对列
- java线程创建个人见解
- 面向对象-属性
- 安卓App开发
- PAT-A-1030. Travel Plan (30)
- Day 11 正则表达式