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. Unity Particle System Sorting Order

    http://answers.unity3d.com/questions/577288/particle-system-rendering-behind-sprites.html

  2. 使用 Elmah一些要注意的问题

    http://www.cnblogs.com/apsnet/archive/2012/04/28/2474730.html 1. Elmah使用后,在发布时,要区分IIS6和IIS7 ,IIS6下 H ...

  3. Python之路【第七篇续】:进程、线程、协程

    Socket Server模块 SocketServer内部使用 IO多路复用 以及 “多线程” 和 “多进程” ,从而实现并发处理多个客户端请求的Socket服务端.即:每个客户端请求连接到服务器时 ...

  4. jQuery 元素的选中, 置顶、上移、下移、置底、删除

    如截图: <ul> <li class="li01" onclick="C_columnSetTop(this)"><i>& ...

  5. HDInsight 指定输出目录 insert overwrite

    基本语法 insert overwrite local directory '/example/demo/' select * from table; 可以格式化输出 insert overwrite ...

  6. 【转】随机函数 rand() srand() 以及seed的原理

    from:http://blog.csdn.net/feige2008/article/details/6943885   标准库<cstdlib>(被包含于<iostream> ...

  7. ZOJ3802 Easy 2048 Again (状压DP)

    ZOJ Monthly, August 2014 E题 ZOJ月赛 2014年8月 E题 http://acm.zju.edu.cn/onlinejudge/showProblem.do?proble ...

  8. [译]Bundling and Minification

    原文:http://www.asp.net/mvc/overview/performance/bundling-and-minification============================ ...

  9. web api 处理发送过来的文件(图片)

    using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.We ...

  10. iOS: Crash文件解析(一)

    iOS Crash文件的解析(一) 开发程序的过程中不管我们已经如何小心,总是会在不经意间遇到程序闪退.脑补一下当你在一群人面前自信的拿着你的App做功能预演的时候,流畅的操作被无情地Crash打断. ...