动态继承

eg:

对于图片来说,可能有PNG, JPG等格式

如果我们有一个ImageZip类, 无法确定继承自那种Image格式(PNGImage or JPGImage ? )

使用工厂函数自动创建类:

defimage_factory(path):# ...ifformat==".gz":image=unpack_gz(path)format=os.path.splitext(image)[1][1:]ifformat=="jpg":returnMakeImageZip(ImageJPG,image)elifformat=="png":returnMakeImageZip(ImagePNG,image)else:raiseException('The format "'+format+'" is not supported.')defMakeImageZIP(base,path):'''`base` either ImageJPG or ImagePNG.'''classImageZIP(base):# ...returnImageZIP(path)defImageZIP(path):path=unpack_gz(path)format=os.path.splitext(image)[1][1:]ifformat=="jpg":base=ImageJPGelifformat=="png":base=ImagePNGelse:raise_unsupported_format_error()classImageZIP(base):# would it be better to use ImageZip_.__name__ = "ImageZIP" ?# ...returnImageZIP(path)

weakref 弱引用

可以处理循环引用问题

importsys# We can use sys.getrefcount(obj) to get refcntclassFoo(object):pass# Create Foo Object A# And print reference countA=Foo()print('Refcnt of A: ',sys.getrefcount(A))# Create a strong reference to A# And check if B is reference to A# Then print A refcnt, it should +1B=Aprint("A is B's referent: ",id(B)==id(A))print('Refcnt of A: ',sys.getrefcount(A))# Create three strong reference to A# Refcnt of A should +3C=AD=AE=Aprint('Refcnt of A: ',sys.getrefcount(A))# Delete E should -1 at A's refcntdelEprint('Refcnt of A: ',sys.getrefcount(A))