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

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第三方库


热门话题
显示图像的RGB编号的java   java JavaFX画布2D游戏:背景变换vs.绘画   在到达maxElementsInMemory之前创建的java DiskMarker   a4j:ajax可用事件的java详尽列表?   java从批处理文件运行jar文件,如果出现错误,则显示meessage   音频Java在背景音乐之上播放声音   用于在FTP中上载文件的java更改目录   尽管设置了必要的属性,java列表项仍不会保持选中状态   java Stanford Core NLP解析与CSV   java使用缓冲区合并热态和冷态   java无法初始化类javax。加密。JCE安全   对这个Java循环如此困惑的输入   java Spring RabbitMQ SimpleRabbitListenerContainerFactory用法   java如何使用jGrowl创建JSF消息   安装jRebel插件后,Netbeans项目中的java源文件夹不可见?   如何在Java中解析复杂的json字符串   java Spark KafkaUtils CreateRDD在键上应用过滤器   try块中的java代码被忽略,为什么?