摘要:
import timedef time_me(fn): def _wrapper(*args, **kwargs): start = time.clock() fn(*args, **kwargs) print "%s cost %s second"%(fn.__name__, time.clock() - start) return _wrapper#这个装饰器可以在方便地统计函数运行的耗时。用来分析脚本的性能是最好不过了。#这样用:@time_medef test(x, y): time.sleep(0.1)@time_medef... 阅读全文
摘要:
#!/usr/bin/env python#coding:utf-8import sysdef show_caller(level=1): def show(func): def wrapper(*args, **kwargs): func(*args, **kwargs) print '{0.f_code.co_filename}:{0.f_lineno}'.format(sys._getframe(level)), "->", func.__name__ return wrapper return show... 阅读全文
摘要:
Frame objectsFrame objects represent execution frames. They may occur in traceback objects (see below).Special read-only attributes: f_back is to the previous stack frame (towards the caller), or None if this is the bottom stack frame; f_code is the code object being executed in this frame; f_locals 阅读全文
摘要:
map(function, iterable, ...)Apply function to every item of iterable and return a list of the results. 阅读全文
摘要:
#coding:utf-8def new(cls, *args, **kwargs): ''' 若cls是函数,则调用之;若cls是类型,则生成一个cls类型的对象 ''' return cls(*args, **kwargs)class Number(object): passclass IntegralNumber(int, Number): ''' 整数类,自定义了一个toInt函数,可以把自己转换为一个int型。 折腾了半天,x=IntegralNumber(3) 最终就是x=3 ''' d 阅读全文
摘要:
#!/usr/bin/env python#coding:utf-8class Borg(object): _share_state = {} def __init__ (self): ''' 将__dict__和_share_state指向了同一个地址 这样会使_share_state的内容始终保持与__dict__同步 由于_share_state是类变量,最终就可以实现多个实例的__dict__保持同步的效果 ''' self.__dict__ = self._share_stateclass... 阅读全文
摘要:
可以使用id>>> print id.__doc__id(object) -> integerReturn the identity of an object. This is guaranteed to be unique amongsimultaneously existing objects. (Hint: it's the object's memory address.)>>> 阅读全文
摘要:
1、闭包(closure)2、装饰器(decorator)3、元类(metaclass)4、对象模型5、其它:new和init、作用域、传值和传引用、super 阅读全文
摘要:
class Singleton(type): def __call__(cls, *args, **kwargs): print "Singleton call" if not hasattr(cls, 'instance'): cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.instance def __new__(cls, name, bases, dct): print "Singleton new"... 阅读全文
摘要:
class MyClass(BaseClass): def __new__(cls, *args, **kwargs): return super(MyClass, cls).__new__(cls, *args, **kwargs)super并不是一个函数,而是一个类名,形如super(B, cls)事实上调用了super类的初始化函数,产生了一个super对象。Python Manuals上介绍:super(type[, object-or-type]) Return a proxy object that delegates method calls to a parent or sib 阅读全文