Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

python实用装饰器代码

$
0
0

python装饰器是一种可以用来对函数进行装饰的面向对象的方法。

当想要对一个已有的模块做一些“修饰工作”,所谓修饰工作就是想给现有的模块加上一些小装饰(一些小功能,这些小功能可能好多模块都会用到),但又不让这个小装饰(小功能)侵入到原有的模块中的代码里去。我们便可以写成一个装饰器,哪些函数需要哪些修饰功能就可以直接在函数前套用装饰器。

type_limit

用途

限制函数的参数和返回值的类型

装饰器代码

class LimitError(Exception): pass def type_limit(*input_type, **return_type): def test_value_type(func): def wrapper(*args, **kwargs): length = len(input_type) if length != len(args): raise LimitError("The list of typeLimit and param " "must have the same length") for index in range(length): t = input_type[index] p = args[index] if not isinstance(p, t): raise LimitError("The param %s should be %s," "but it's %s now!" % (str(p), t, type(p))) res = func(*args, **kwargs) if "return_type" in return_type: limit = return_type["return_type"] if not isinstance(res, limit): raise LimitError( "This function must return a value that is %s," "but now it's %s" % (limit, type(res))) return res return wrapper return test_value_type 使用方法

@type_limit(int, int, return_type=int) def add(a, b): return a + b

exe_time

用途

输出函数运行时间

装饰器代码

import time def exe_time(func): def wrapper(*args, **kwargs): t0 = time.time() sys.stdout.write('\033[0;32;0m') print "-----------------------------------" print "%s,function \033[4;32;0m%s()\033[0m\033[0;32;0m start" \ % (time.strftime("%X", time.localtime()), func.__name__) sys.stdout.write('\033[0m') res = func(*args, **kwargs) sys.stdout.write('\033[0;32;0m') print "%s,function \033[4;32;0m%s()\033[0m\033[0;32;0m end" \ % (time.strftime("%X", time.localtime()), func.__name__) print "%.3fs taken for function \033[4;32;0m%s()\033[0m\033[0;32;0m" \ % (time.time() - t0, func.__name__) print "-----------------------------------" sys.stdout.write('\033[0m') return res return wrapper 使用方法

@exe_time def func(): for i in range(100000): pass


Viewing all articles
Browse latest Browse all 9596

Trending Articles