python 类修饰器
1. 修改类函数。
场景: 如果要给一个类的所有方法加上计时,并打印出来。demo如下:
# -*- coding:utf-8 -*-
import time
def time_it(fn):
"Example of a method decorator"
def decorator(*args, **kwargs):
t1=time.time()
ret = fn(*args, **kwargs)
print '\t\t%d seconds taken for %s'%(time.time()-t1, fn.__name__)
return ret return decorator def class_decorator(*method_names):
def class_rebuilder(cls):
"The class decorator example"
class NewClass(cls):
"This is the overwritten class"
def __getattribute__(self, attr_name):
attr_val = super(NewClass, self).__getattribute__(attr_name)
if callable(attr_val) and attr_name in method_names:
return time_it(attr_val)
return attr_val return NewClass
return class_rebuilder @class_decorator('first_method', 'second_method')
class MySecondClass(object):
"""
This class is decorated
"""
def first_method(self, *args, **kwargs):
print "\tthis is a the MySecondClass.first_method"
time.sleep(2) def second_method(self, *args, **kwargs):
print "\tthis is the MySecondClass.second_method"
time.sleep(1) if __name__ == "__main__":
print "::: With a decorated class :::"
z = MySecondClass()
z.first_method()
z.second_method()
好处相比函数修饰器要稍微简洁一点(在类有很多方法时)
2. 增加类成员
场景:比如统一给所有的模型增加id, created_time属性
# -*- coding:utf-8 -*-
def addAttrs(*attrs):
def re_build(cls):
class newClass(cls):
def __init__(self,*args, **kws):
for attr in attrs:
setattr(self, attr, None)
self.__id = id
super(newClass, self).__init__(*args, **kws)
return newClass
return re_build @addAttrs('id', 'created_time')
class DBModelOne(object):
def __init__(self, *args, **kwargs):
pass if __name__=='__main__':
m = DBModelOne(5)
print m.id, m.created_time
or
# -*- coding:utf-8 -*-
import time
def cd(cls):
def init(*args, **kwargs):
cls_obj = cls(*args, **kwargs)
setattr(cls_obj, 'id', time.time())
return cls_obj
return init
@cd
class A(object):
def __init__(self, name, age, sex='f'):
self.name=name
self.age=age
self.sex=sex
def s(self):
print self.id if __name__=='__main__':
print type(A)#<type 'function'>
a=A('Alice', 22)
print type(a)#<class '__main__.A'>
print a#<__main__.A object at 0x7fe617baa690>
print a.name, a.age, a.sex#Alice 22 f
a.s()
转载请注明来自:http://www.cnblogs.com/Tommy-Yu/p/5457751.html
python 类修饰器的更多相关文章
- python函数修饰器(decorator)
python语言本身具有丰富的功能和表达语法,其中修饰器是一个非常有用的功能.在设计模式中,decorator能够在无需直接使用子类的方式来动态地修正一个函数,类或者类的方法的功能.当你希望在不修改函 ...
- python中用修饰器进行异常日志记录
当脚本中需要进行的的相同的异常操作很多的时候,可以用修饰器来简化代码.比如我需要记录抛出的异常: 在log_exception.py文件中, import functools import loggi ...
- Python 函数修饰器
# 一.用函数修饰函数 #!/usr/bin/python3 def decorate_func(func): def call(*args, **kwargs): print('you have c ...
- python decorator 修饰器
decorator 就是给函数加一层皮,好用! 1 from time import ctime 2 3 def deco(func): 4 def wrappedFunc(*args, **kwar ...
- Python学习-修饰器 - itemgetter的妙用
下面这篇对装饰器讲的很好,懂了. http://python.jobbole.com/85056/ <简单 12 步理解 Python 装饰器> 使用装饰器非常简单(见步骤10),但是写装 ...
- python类装饰器即__call__方法
上一篇中我对学习过程中的装饰器进行了总结和整理,这一节简单整理下类装饰器 1.类中的__call__方法: 我们在定义好一个类后,实例化出一个对象,如果对这个对象以直接在后边加括号的方式进行调用,程序 ...
- python 之修饰器
from functools import update_wrapper def debug(func): def wrapper(): print "[DEBUG]: enter {}() ...
- python 类装饰器
class Test(): def __init__(self, func): print('装饰器1') self.__func = func def __call__(self): print(' ...
- python 通用 修饰器
import functools def log(option): def dec(func): def swapper(*arg, **karg): functools.update_wrapper ...
随机推荐
- 仿照jquery封装一个自己的js库(一)
所谓造轮子的好处就是复习知识点,加深对原版jquery的理解. 本文系笔者学习jquery的笔记,记述一个名为"dQuery"的初级版和缩水版jquery库的实现.主要涉及知识点包 ...
- Markdown常用用法
很早之前就听过Markdown,一直没用,用过才发现,原来这么好用,迷人,就好比一位知性.大方.成熟.美丽的少妇一样深深吸引着我,特深夜把学习的笔记记录下. 引用 ">"最好 ...
- GLEW OpenGL Access violation when using glGenVertexArrays
http://stackoverflow.com/questions/20766864/glew-opengl-access-violation-when-using-glgenvertexarray ...
- iOS后台播放
### 音乐后台播放 * .当程序进入后台的时候,开启后台任务 ``` - (void)applicationDidEnterBackground:(UIApplication *) { // 开启后 ...
- 使用Topshelf 开发windows服务
在业务系统中,我们为了调度一些自动执行的任务或从队列中消费一些消息,所以基本上都会涉及到后台服务的开发.如果用windows service开发,非常不爽的一件事就是:调试相对麻烦,而且你还需要了解 ...
- Robot Framework--01 创建简单工程示例
1.新建Project: 填写name,选择Type为Dirctory,路径根据自己需要选择,建议最好不要在中文路径下,以免发生问题:
- Windows下安装Tomcat服务
startup.bat中添加以下内容 setlocal SET JAVA_HOME=D:\Program Files\Java\jdk1.8.0_05 SET CATALINA_HOME=D:\Pro ...
- c# 中使用memcached
1.首先下载memcached 服务端 2.使用Enyim.Caching .Net 客户端 3.配置web.config <sectionGroup name="QuickBo ...
- setTimeout和setInterval的各自使用场景
默认的 setTimeout 只执行一次, 清除用clearTimeout setInterval 每间隔指定的时间, 就执行一次, 清除用clearInterval 但是, setTimeout也可 ...
- CF451A Game With Sticks 水题
Codeforces Round #258 (Div. 2) Game With Sticks A. Game With Sticks time limit per test 1 second mem ...