标签:lte ogg python tor self style div 其他 比较
“一般来说,装饰器是一个函数,接受一个函数(或者类)作为参数,返回值也是也是一个函数(或者参数)”
(user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances, and certain class instances themselves are callable; extensions may define additional callable object types).
1 class cost_time_logger(object): 2 def __init__(self, func): 3 self.func = func 4 5 def __call__(self, *args, **kwargs): 6 import time 7 begin = time.time() 8 try: 9 return self.func(*args, **kwargs) 10 finally: 11 print(‘func %s cost %s‘ % (self.func.__name__, time.time() - begin)) 12 13 @cost_time_logger 14 def complex_func(num): 15 ret = 0 16 for i in xrange(num): 17 ret += i * i 18 return ret 19 20 if __name__ == ‘__main__‘: 21 print complex_func(100000)
1 def singleton(cls): 2 instances = {} 3 def getinstance(): 4 if cls not in instances: 5 instances[cls] = cls() 6 return instances[cls] 7 return getinstance 8 9 @singleton 10 class MyClass: 11 pass 12 13 if __name__ == ‘__main__‘: 14 print type(MyClass)
标签:lte ogg python tor self style div 其他 比较
原文地址:http://www.cnblogs.com/xybaby/p/6274283.html