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 类修饰器的更多相关文章

  1. python函数修饰器(decorator)

    python语言本身具有丰富的功能和表达语法,其中修饰器是一个非常有用的功能.在设计模式中,decorator能够在无需直接使用子类的方式来动态地修正一个函数,类或者类的方法的功能.当你希望在不修改函 ...

  2. python中用修饰器进行异常日志记录

    当脚本中需要进行的的相同的异常操作很多的时候,可以用修饰器来简化代码.比如我需要记录抛出的异常: 在log_exception.py文件中, import functools import loggi ...

  3. Python 函数修饰器

    # 一.用函数修饰函数 #!/usr/bin/python3 def decorate_func(func): def call(*args, **kwargs): print('you have c ...

  4. python decorator 修饰器

    decorator 就是给函数加一层皮,好用! 1 from time import ctime 2 3 def deco(func): 4 def wrappedFunc(*args, **kwar ...

  5. Python学习-修饰器 - itemgetter的妙用

    下面这篇对装饰器讲的很好,懂了. http://python.jobbole.com/85056/ <简单 12 步理解 Python 装饰器> 使用装饰器非常简单(见步骤10),但是写装 ...

  6. python类装饰器即__call__方法

    上一篇中我对学习过程中的装饰器进行了总结和整理,这一节简单整理下类装饰器 1.类中的__call__方法: 我们在定义好一个类后,实例化出一个对象,如果对这个对象以直接在后边加括号的方式进行调用,程序 ...

  7. python 之修饰器

    from functools import update_wrapper def debug(func): def wrapper(): print "[DEBUG]: enter {}() ...

  8. python 类装饰器

    class Test(): def __init__(self, func): print('装饰器1') self.__func = func def __call__(self): print(' ...

  9. python 通用 修饰器

    import functools def log(option): def dec(func): def swapper(*arg, **karg): functools.update_wrapper ...

随机推荐

  1. C语言getopt()函数的使用

    getopt(分析命令行参数)     相关函数表头文件         #include<unistd.h>定义函数         int getopt(int argc,char * ...

  2. 常用JS效果 不断进步贴 不停更新~ 纪念用~

    常用效果 JS  都是Jquery  没有特殊说明 1.选项卡  用的JQuery  以后学好点再来对比 看下 /* * @parent 最外层父级元素 * @EventElement 触发事件元素 ...

  3. python 默认全局变量

    python 内置默认全局变量print (vars()) __doc__ #py文件头部的注释 '''我是一个注释例子''' print (vars()) __file__ #当前文件路劲__pac ...

  4. 判断QQ是否在线

    <html> <body> ggygygygy<br> <td><a href="http://wpa.qq.com/msgrd?V=1 ...

  5. mysql 如何用一条SQL将一张表里的数据插入到另一张表 3个例子

    1. 表结构完全一样 insert into 表1 select * from 表2  2. 表结构不一样(这种情况下得指定列名) insert into 表1 (列名1,列名2,列名3) selec ...

  6. [Ljava.lang.String和java.lang.String区别

    在做项目时报了一个got class [Ljava.lang.String的提示,当时看到[Ljava.lang.String这个时,感觉有点怪怪的,第一次遇到这种情况.最后在网上查了下才明白.是数组 ...

  7. Linux动态库的编译与使用 转载

    http://hi.baidu.com/linuxlife/blog/item/0d3e302ae2384d3a5343c1b1.html Linux下的动态库以.so为后缀,我也是初次在Linux下 ...

  8. Vue 入门指南 JS

    Vue 入门指南 章节导航 英文:http://vuejs.org/guide/index.html 介绍 vue.js 是用来构建web应用接口的一个库 技术上,Vue.js 重点集中在MVVM模式 ...

  9. 【CISP笔记】安全漏洞与恶意代码(2)

    恶意代码自我保护 进程保护 进程守护 超级权限 检测对抗 反动态调试 反静态调试 恶意代码检测技术 特征码扫描 沙箱技术 行为检测 恶意代码分析技术 静态分析 需要实际执行恶意代码,它通过对其二进制文 ...

  10. 滑雪 why WA

    滑雪 Time Limit: 1 Sec  Memory Limit: 64 MBSubmit: 587  Solved: 219 Description 小明喜欢滑雪,因为滑雪的确很刺激,可是为了获 ...