使用python中的对象和类的各种工具
objecttools的Python项目详细描述
使用python中的对象和类的各种工具
缓存属性
工作方式与普通属性类似,但返回的值被缓存:
fromobjecttoolsimportCachedPropertyclassExpensiveOperations(object):@CachedPropertydefexpensive_attribute(self):returnself.calculate()# To make it settable@expensive_attribute.setterdefexpensive_attribute(self,value):pass# To make it deletable@expensive_attribute.deleterdefexpensive_attribute(self):passe=ExpensiveOperations()e.other_attribute=1print(e.expensive_attribute)# Takes a long time.print(e.expensive_attribute)# Very quick; just retrieve from cachev=e.expensive_attributee.other_attribute=2# expensive_attribute should be different now!print(e.expensive_attribute)# Old value that is wrong.dele.expensive_attributeprint(e.expensive_attribute)# Takes a long time, but returns new value.e.other_attribute=1# Reset to known valuee.expensive_attribute=vprint(e.expensive_attribute)# Correct value!
单重态
fromobjecttoolsimportSingletonSentinel=Singleton.create('Sentinel')Sentinel()isSentinel()# Trued.get('missing_value',Sentinel())isSentinel()# TrueclassGlobalState(dict,metaclass=Singleton):attr=0gs=GlobalState()gs['value']=7gs.attr=1print(GlobalState()['value']+GlobalState().attr)# 8
对于Python2和3的兼容性,请将其用作装饰符:
@Singleton.as_decoratorclassClass(object):pass
对象代理
创建一个对象的弱可引用代理,该对象支持 操作:
fromobjecttoolsimportObjectProxyls=[1,2,3]proxy=ObjectProxy(ls)proxy.append(4)proxy+=[5,6]proxy[2:4]=[7,8,9]print(ls)# [1, 2, 7, 8, 9, 5, 6]
可串行化
创建对象的可序列化形式(用于酸洗)
fromobjecttoolsimportSerializableFunction,SerializableConstantimportpicklefile=open('file.txt','w')f=lambdafile,a:file.write(a)try:# Cannot pickle files, even though it is a global constantgile=pickle.loads(pickle.dumps(file))exceptTypeError:gile=pickle.loads(pickle.dumps(SerializableConstant('file',__name__))).valuetry:# Cannot pickle functions if they are lambdas# Or are inner functions# Or are deleted after creation# Or are methodsg=pickle.loads(pickle.dumps(f))exceptpickle.PicklingError:g=pickle.loads(pickle.dumps(SerializableFunction(f)))g(gile,'data')# Works
安装
来自PyPI
$ pip install objecttools
来源
$ git clone 'https://github.com/MitalAshok/objecttools.git'
$ python ./objecttools/setup.py install