python中的装饰器
来源:互联网 发布:卡通农场数据恢复 编辑:程序博客网 时间:2024/04/30 00:49
python中的装饰器详解
1. 装饰器的定义:
在写代码的时候, 我们要遵循 开发封闭 原则, 这个原则不仅适用于面向对象的开发, 也使用与函数式编程.
简单的来说就是:
- 已经实现的功能代码不允许修改, 但可以扩展,
- 封闭: 以实现的功能开发;
- 开放: 对扩展的开发
@函数名 是python的一种 语法糖;
2. 装饰器的代码实例:
a. 对参数不确定的函数进行装饰
参数用 ( * args, **kwargs), 自动适应变参和命名参数
# -*- coding:utf8 -*-def deco(func): def _deco(*args, **kwargs): print("before %s called." % func.__name__) ret = func(*args, **kwargs) print(" after %s called. result: %s" % (func.__name__, ret)) return ret return _deco@decodef myfunc(a, b): print(" myfunc(%s,%s) called." % (a, b)) return a+b@decodef myfunc2(a, b, c): print(" myfunc2(%s,%s,%s) called." % (a, b, c)) return a+b+cmyfunc(1, 2)myfunc(3, 4)myfunc2(1, 2, 3)myfunc2(3, 4, 5)
b. 让装饰器代类参数
def deco(func): def _deco(*args, **kwargs): print("before %s called." % func.__name__) ret = func(*args, **kwargs) print(" after %s called. result: %s" % (func.__name__, ret)) return ret return _deco@decodef myfunc(a, b): print(" myfunc(%s,%s) called." % (a, b)) return a+b@decodef myfunc2(a, b, c): print(" myfunc2(%s,%s,%s) called." % (a, b, c)) return a+b+cmyfunc(1, 2)myfunc(3, 4)myfunc2(1, 2, 3)myfunc2(3, 4, 5)
c. 装饰器带 类, 参数, 并拆分其他公共文件到其他py文件中, 同时演示一个函数应用对应多个装饰器
一个py文件
def deco(func): def _deco(*args, **kwargs): print("before %s called." % func.__name__) ret = func(*args, **kwargs) print(" after %s called. result: %s" % (func.__name__, ret)) return ret return _deco@decodef myfunc(a, b): print(" myfunc(%s,%s) called." % (a, b)) return a+b@decodef myfunc2(a, b, c): print(" myfunc2(%s,%s,%s) called." % (a, b, c)) return a+b+cmyfunc(1, 2)myfunc(3, 4)myfunc2(1, 2, 3)myfunc2(3, 4, 5)
另一个py文件
# -*- coding:gbk -*-'''示例: 装饰器带类参数,并分拆公共类到其他py文件中同时演示了对一个函数应用多个装饰器'''from mylocker import *class example: @lockhelper(mylocker) def myfunc(self): print(" myfunc() called.") @lockhelper(mylocker) @lockhelper(lockerex) def myfunc2(self, a, b): print(" myfunc2() called.") return a + bif __name__=="__main__": a = example() a.myfunc() print(a.myfunc()) print(a.myfunc2(1, 2)) print(a.myfunc2(3, 4))
阅读全文
0 0
- Python中的装饰器
- python中的装饰器
- python中的装饰器
- python中的装饰器
- Python中的装饰器
- Python中的装饰器
- python中的装饰器
- python中的装饰器
- python中的装饰器
- Python中的装饰器
- Python中的装饰器
- python中的装饰器
- Python中的装饰器
- Python中的装饰器
- Python 中的装饰器
- python中的装饰器
- Python中的装饰器
- python中的装饰器
- 热键与快捷键的区别
- Java之多线程加强(多线程调度与控制)
- 初识.net界面程序(11)--实现界面登陆
- linux配置java环境变量(详细)
- Html-Css基础知识
- python中的装饰器
- asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_
- Ajax学习(三):XML及Json与Ajax配合使用
- Android毕业设计及论文答辩经验分享
- 图像
- 什么是线程安全和线程不安全
- CSS项目技巧:固定元素在顶部以及position解读
- CentOS-7.0.中安装与配置Tomcat-7的方法
- iOS 数字、字母和字符串的判断