使生活更轻松的对象实用程序

sloot.object的Python项目详细描述


https://travis-ci.org/samjy/sloot.object.svg?branch=master

基本用法

>>> from sloot.object import dictobj
>>> d = dictobj({'a': 'a', 'b': 'b'}, c='c')
>>> print(d)
dictobj({'a': 'a', 'b': 'b', 'c': 'c'})
>>> d.a
'a'
>>> d['a']
'a'
>>> d.a = 3
>>> d.a
3
>>> d['a'] = 42
>>> d.a
42
>>> print(d)
dictobj({'a': 42, 'c': 'c', 'b': 'b'})
>>> print(dict(d))
{'a': 42, 'c': 'c', 'b': 'b'}

setattr在继承对象中的行为

>>> class T(dictobj):
...   classvar = 'classvar'
...   def f(self):
...     return 'f'
...   @property
...   def prop(self):
...     return getattr(self, '_prop', 'prop')
...   @prop.setter
...   def prop(self, value):
...     self._prop = value
...
  • 方法和类属性不会被覆盖并转到dict:

    >>> t = T({'classvar': 1, 'f': 2, 'prop': 3})
    >>> t.classvar  # access the class attribute
    'classvar'
    >>> t['classvar']  # access the dict entry
    1
    >>> t.classvar = 5  # we don't overwrite class attributes, this goes to dict
    >>> t.classvar  # this is the class attribute
    'classvar'
    >>> t['classvar']
    5
    >>> t.f  # access the class method
    <bound method T.f of T({'classvar': 1, 'f': 2, 'prop': 3})>
    >>> t['f']  # access the dict entry
    2
    >>> t.f = 4  # we don't overwrite the method, this goes to the dict
    >>> t.f
    <bound method T.f of T({'classvar': 1, 'f': 2, 'prop': 3})>
    >>> t['f']
    4
    
  • 使用getter和setter属性:

    >>> t.prop  # get the property
    'prop'
    >>> t['prop']  # get the dict entry
    3
    >>> t.prop = 'newprop'  # use property setter
    >>> t.prop
    'newprop'
    >>> t['prop']
    3
    
  • 否则将更新dict:

    >>> t.a = 42
    >>> t['a']
    42
    >>> t.a
    42
    

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

推荐PyPI第三方库


热门话题
java如何忽略缓冲读取器中在“”之后的行的其余部分,或行上的特定字符?   java在db中创建空对象或稍后保存   java如何实现UI无关的后台工作任务   java未能在Android中从BaseAdapter扩展的类中启动Tactivity?   java斐波那契迭代移动数组[]   安卓从文件读取提供了java。木卫一。StreamCorruptedException:无效的流标头:73720027   java计算矩形中的六边形数?   仅使用Java 1.5(或更早版本)读写XML   java如果所有元素都以相同的bucked结尾,为什么要进行大小调整?   java Apache POI Excel在xx中发现无法读取的内容。xlsx   swing我可以在普通java应用程序中使用GWTGUI吗?   来自自定义Java客户端的http删除请求的行为与邮递员不同   运行批处理文件时,java当前目录无效   使用TypeReference将java字符串转换为ArrayList<STRING>   documentlistener突出显示所有匹配词Java