使用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

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java是否可以创建一个正则表达式来查找与模式不匹配的字符串?   使用“debugUnreturnedConnectionStackTraces”进行java调试连接丢失   java如何在openLDAP中禁用/启用用户帐户?   java无法从jsoup api获取某些类   java无法从APK提取XML文件   如何在linux命令行中替换多个文件中的字符串   java学生班。如何根据单位输入打印成绩?   java有没有办法将Struts配置为绑定null而不是空字符串?   python使用OpenCV[Java]检测简单几何形状   java文件。isFile()和文件。isDirectory()返回false   java Fetch有条件地加入hibernate,还是将实体设计更改为子实体上的条件Fetch?   java lombok@Data generated setter是否对成员对象(如映射)执行深度复制?   java如何使JLabel从下一行开始   java Gradle依赖解决了配置文件的问题