Entries tagged “#装饰器”

Tue 26 April 2016

Python单例模式的实现

由于实现的方式很多,先来3种。 1. 类实例实现的单例装饰器 import functools class Singleton(object): def __init__(self): self.instances = {} def __call__(self, cls): @functools.wraps(cls) def wrapper(*args, **kwargs) if not self.instances.get(cls): self.instances[cls] = cls(*args, **kwargs) return self.instances[cls] return wrapper singleton = Singleton() # 用法 @singleton class Test(object ... read more
Sat 26 March 2016

Python单层装饰器小记

解释器什么时候处理装饰器? 答: Python解释器加载代码的时候. 例如, sleep.py 代码如下 import functools import time def timer(func): print("handle decorator") @functools.wraps(func) def wrapper(*args, **kwargs): start = time.time() rtn = func(*args, **kwargs) cost = time.time() - start print("cost %f s") % cost return rtn return wrapper @timer def sleep(seconds): time.sleep ... read more
 

Tags