点符号对象
dotobject的Python项目详细描述
dotobject v 1.2.1
点符号对象
点允许您以点表示法格式定义对象。
为了使用dot notation对象,您需要子类dot并定义自己的load和可选的save方法。
背景
dot notation对象最初设计为python的redis客户机的基本库。因此,名称“load”和“save”来自。其思想是让python对象通过编写obj.item=“value”,将redis键“obj.item”设置为“value”值。 一旦它检测到您正在检索该值,它就会从redis获取最新版本。但同时,它给你一个懒惰的对象,直到它真正需要redis的值。
因此,dot notation对象基本上是一个惰性对象,一旦定义了它的“load”和“save”方法,它将在保存或检索对象时运行这些方法。
参数
- 根名称:字符串,可选。
- 它用于覆盖点对象的根名称。
- int_以:string开始,可选。默认值:i
- 它用于识别整数部分,因为python不允许整数作为属性。
返回
在实际使用时将对其求值的惰性对象。
示例
- 定义自己的点
>>> from dot import Dot >>> class This(Dot): ... def __init__(self, *args, **kwargs): ... super(This, self).__init__(*args, **kwargs) ... self.items = {} ... def load(self, paths): ... return {i: self.items[i] if i in self.items else "value %s" % i for i in paths} ... def save(self, path, value): ... self.items[path] = value ...
- 创建点对象
>>> this = This() >>> aa = this.part1.part2.part3.part4 >>> aa <Lazy object: this.part1.part2.part3.part4> >>> print(aa) value this.part1.part2.part3.part4 >>> aa value this.part1.part2.part3.part4
- 点对象在批处理中求值
>>> this = This() >>> aa = this.part1 >>> aa <Lazy object: this.part1> >>> bb = this.part2 >>> bb <Lazy object: this.part2> >>> print(aa) value this.part1 >>> aa value this.part1 >>> bb value this.part2
- 处理将整数作为部分的路径
>>> bb = this.part1.part2.i120 >>> bb <Lazy object: this.part1.part2.120> >>> print bb value this.part1.part2.120
- 处理点,如字典键
>>> cc = this['part1.part2.part4'] >>> cc <Lazy object: this.part1.part2.part4> >>> dd = this['part1.%s.part4' % 100] >>> dd <Lazy object: this.part1.100.part4> >>> path = 'part1.part2' >>> this[path] = 'This was set by a dynamic key.' >>> this.path This was set by a dynamic key.
- 保存点
>>> this.part1.part2.part3.part4 = "new value" >>> zz = this.part1.part2.part3.part4 >>> zz new value
- 更改根名称
>>> class That(This): ... pass >>> that = That() >>> aa = that.something >>> print(aa) value that.something >>> bb = this.something >>> bb <Lazy object: this.something>
- 刷新缓存
>>> aa = this.part1 >>> print aa value this.part1 >>> bb = this.part1 # reads from the cache >>> this.flush() >>> bb = this.part1 # Will evaluate this.part1 again