从metaclass到__init__, new , __call__到单例模式
到threading中的with到__enter__, exit
到字典hashmap原理的__hash__, eq
到Flask的配置文件__dir__的一些类信息
__add__的原理
获取传入参数的kwargs的技巧, 框架中使用
class Foo ( object ) :
def __new__ ( cls, * args, ** kwargs) :
res = kwargs. get( "many" , "" )
print ( args)
print ( kwargs)
print ( res)
return 1
obj = Foo( "url" , many= True )
print ( obj)
import threading
import time
class Singleton ( object ) :
lock = threading. RLock( )
instance = None
def __new__ ( cls, * args, ** kwargs) :
with cls. lock:
if not cls. instance:
time. sleep( 2 )
cls. instance = super ( ) . __new__( cls)
return cls. instance
def task ( arg) :
obj = Singleton( )
print ( id ( obj) )
def main ( ) :
for i in range ( 10000 ) :
t = threading. Thread( target= task, args= ( i, ) )
t. start( )
if __name__ == "__main__" :
main( )
class Foo ( object ) :
def __init__ ( self, num) :
self. num = num
def __add__ ( self, other) :
return self. num + other. n
class Bar ( object ) :
def __init__ ( self, n) :
self. n = n
f = Foo( 1 )
b = Bar( 2 )
res = f + b
print ( res)