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 ...
随机推荐
- Google
1. Google Play: Google Play是谷歌官方的的应用市场, Google Play 服务通常会在 Android 装置上自动更新. http://baike.baidu.com/l ...
- SPL--spl_autoload_register
spl_autoload_register() : 调用未定义类时,系统会按顺序调用注册到spl_autoload_register()函数的所有函数,而不是调用__autoload函数. 解决问题: ...
- nuget包管理器控制台下的powershell脚本介绍
http://personball.com/powershell/2016/07/15/powershell-tips 定制自己的powershell,减少重复工作 安装一系列自己的常用nuget包 ...
- 序列化与反序列化成XML
http://blog.itpub.net/12639172/viewspace-490786/ 现在XML都普遍的用到了很多地方,它的平台无关.方便.结构化.适用性的特点让人不得不去接受它,在C#中 ...
- onscroll事件的浏览器支持
window和普通div对象的scroll事件,被全部浏览器支持,其他元素的scroll事件,仅部分浏览器支持,如下图 出处: http://w3help.org/zh-cn/causes/SD901 ...
- ul li 下的元素内容垂直居中
CSS: <style> * {;; } li { list-style: none; } li span { border: 1px solid red; height: 100px; ...
- iOS- Terminating app due to uncaught exception 'NSRangeException'
错误描述: Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM object ...
- 弹出框一 之 基于bootstrap和jquery的自定义弹出框
(function ($) { window.Ewin = function () { var html = '<div id="[Id]" class="moda ...
- Linux服务器管理: 系统的进程管理终止进程kill命令
在Linux中如何用kill终止进程: kill -l [root@localhost~]#kill -l 可以看到kill中有很多的 常用: -1 是重启一个进程 -9 是强制杀死进程 ...
- JavaScript 学习笔记 -- Function
JS 中 函数.继承.闭包.作用域链... 一直都是硬伤,一碰到这样的问题头就大了.但是如果我继续着说:我不会,就真的无药可救了.要勇敢地说出:我的字典里就没有不会这个词,吼吼..正好昨天在书城里看了 ...