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. JS数组类型检测

    在强类型语言,数组类型检测是非常容易的事情(typeof就可以解决),而在弱语言JS数据类型就很容易混淆了. JS中常见的数据类型有:number.string.boolean.undefined.f ...

  2. CURL常用命令--update20151015

    下载单个文件,默认将输出打印到标准输出(STDOUT)中 curl http://www.centos.org 通过-o/-O选项保存下载的文件到指定的文件中:-o:将文件保存为命令行中指定的文件名的 ...

  3. 使用Xunit来进行单元测试

    不管你爱与不爱,单元测试对于一个软件的长治久安还是必不可少的一环.在Visual Studio 2012后,VS中的测试浏览器也能与第三方的集成了,用起来还是非常方便的.目前在.Net框架下的测试工具 ...

  4. mysql Table 'performance_schema.session_variables' doesn't exist

    CMD  进入MYSQL的安装目录..Bin 下 执行 mysql_upgrade -u root -p --force 输入密码..然后等待一会儿..会跑一些东西..然后重启服务

  5. 新浪微博客户端(59)-hitTest withEvent方法的使用说明

    iOS中的触摸事件总是由最顶层的View首先得到的,当这个View得到该触摸事件的时候可以选择通过 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEv ...

  6. c#之Redis队列

    摘要 这两天一直在考虑redis队列:一个生产者,多个消费者的情况,这里弄了一个demo进行测试. 一个例子 关于如何引用Redisclient 可以参考之前的这篇文章:c#之Redis实践list, ...

  7. wtforms 使用

    wtforms是一个表单模板库, 下面以修改密码表单为例简单说明其用法. 我们可以用python代码定义form的基本元素, 比如用户名/邮箱, 并给定各个元素的validation条件. 然后在re ...

  8. 2015年11月25 Java基础系列(二)Thread Runnable线程初级讲解

    序,线程是比进程小的进程,非常广泛的被使用. 一.继承Thread实现线程操作 1.注意setDaemon(boolean)方法,参数为true时为守护线程,参数为false时为用户线程. 守护线程的 ...

  9. ubuntu安装php常见错误集锦

    一.configure 报错 1.错误类型: Configure: error: Please reinstall the libcurl distribution-easy.h should be ...

  10. 全架构PaaS TAE 2.0的Docker实践

    推荐链接: http://www.infoq.com/cn/news/2015/07/paas-tae-docker