python decorator
来源:互联网 发布:淘宝卖家插件哪个好 编辑:程序博客网 时间:2024/06/07 10:23
def deco(func): def _deco(): print("before myfunc called.") func() print("after myfunc called.") return _deco@deco #相当于执行myfunc = deco(myfunc),把myfunc变成了deco定义的_deco()函数def myfunc(): print("myfunc() called.")myfunc()myfunc()
# -*- coding:gbk -*-'''示例8: 装饰器带类参数'''class locker: def __init__(self): print("locker.__init__() should be not called.") @staticmethod def acquire(): print("locker.acquire() called.(这是静态方法)") @staticmethod def release(): print(" locker.release() called.(不需要对象实例)")def deco(cls): '''cls 必须实现acquire和release静态方法''' def _deco(func): def __deco(): print("before %s called [%s]." % (func.__name__, cls)) cls.acquire() try: return func() finally: cls.release() return __deco return _deco@deco(locker)def myfunc(): print(" myfunc() called.")myfunc()myfunc()
比如:多个decorator
1234@decorator_one
@decorator_two
def
func():
pass
相当于:
1func
=
decorator_one(decorator_two(func))
比如:带参数的decorator:
123@decorator
(arg1, arg2)
def
func():
pass
相当于:
1func
=
decorator(arg1,arg2)(func)
这意味着decorator(arg1, arg2)这个函数需要返回一个“真正的decorator”。
内置的装饰器有三个,分别是staticmethod、classmethod和property,作用分别是把类中定义的实例方法变成静态方法、类方法和类属性。
参考链接:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
阅读全文
0 0
- python decorator
- python decorator
- python decorator
- python decorator
- Python - Decorator
- Python decorator
- python decorator
- python decorator
- Python Decorator
- Python Decorator
- python decorator
- Python Decorator
- python decorator
- Python - decorator
- Python Decorator
- Python - Decorator
- python decorator
- Python decorator
- 9.17NOIP模拟赛
- AndroidQQ登录
- 7-26 单词长度(15 分)
- CentOS7之常用服务
- jQuery学习入门(一)
- python decorator
- Object-C的编译命令
- Nginx编译安装
- hdfs——hadoop文件读写操作
- 在共享内存实现 Redis(上)
- HDU 5783 Divide the Sequence——贪心
- shiro中的请求参数
- android UiAutomator生成测试报告的基本方法封装
- BZOJ4538 网络 [树链剖分]