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. 和安全有关的那些事(非对称加密、数字摘要、数字签名、数字证书、SSL、HTTPS及其他)

    转自http://blog.csdn.net/bluishglc/article/details/7585965 对于一般的开发人员来说,很少需要对安全领域内的基础技术进行深入的研究,但是鉴于日常系统 ...

  2. VC----Class Style类风格和窗口风格

    CS_BYTEALIGNCLIENT:以字节边界来对齐窗口客户区,这个风格会影响 窗口 的宽度和水平位置.实际上没有看到效果. CS_BYTEALIGNWINDOW:以字节边界来对齐窗口,这个风格会影 ...

  3. Python之路【目录】 2

    http://www.cnblogs.com/wupeiqi/articles/4938499.html

  4. Nginx + spawn-fcgi- Ubuntu中文

    Nginx - Ubuntu中文 页面 讨论 查看源代码 历史   导航 首页 最近更改 随机页面 页面分类 帮助 编辑 编辑指南 沙盒 新闻动态 字词处理 工具 链入页面 相关更改 特殊页面 打印版 ...

  5. MYSQL的锁介绍,以及死锁发生情况-带例子

    mysql锁能在并发情况下的mysql进行更好的优化 MySQL有三种锁的级别:页级.表级.行级,这3种锁的特性可大致归纳如下: 表级锁:开销小,加锁快:不会出现死锁:锁定粒度大,发生锁冲突的概率最高 ...

  6. mysql SELECT FOR UPDATE语句使用示例

    以MySQL 的InnoDB 为例,预设的Tansaction isolation level 为REPEATABLE READ,在SELECT 的读取锁定主要分为两种方式:SELECT ... LO ...

  7. 贴上自己写的代码-jq隐藏事件

  8. 如何让图片在垂直方向与 div的底部对齐 水平居中

    需要图片的绝对定位postion: absolute. 一般定位时, 是用div去定位. 一般不直接用 非div去"绝对/相对"定位. 如不直接用 等去定位. 因为这些好像不好定位 ...

  9. ASP.NET MVC 4 的JS/CSS打包压缩功能-------过滤文件

    今天在使用MVC4打包压缩功能@Scripts.Render("~/bundles/jquery") 的时候产生了一些疑惑,问什么在App_Start文件夹下BundleConfi ...

  10. Linux运维初级教程(二)账户与安全

    知识点 用户ID为UID,组ID为GID,UID=0表示超级管理员即root. 一个用户只可以加入一个基本组,但是可以同时加入多个附加组. 创建用户时,系统默认会自动创建同名的组,并设置用户加入该基本 ...