数组操作的Python属性

时间:2015-05-20 13:07:56

标签: python python-3.x

使用Python属性(setter和getter)时,通常使用以下内容:

class MyClass(object):
    ...        
    @property
    def my_attr(self):
        ...

    @my_attr.setter
    def my_attr(self, value):
        ... 

但是,有没有类似的方法来追加/删除数组?例如,在两个对象之间的双向关系中,当删除对象A时,最好取消引用对象B中与A的关系。我知道SQLAlchemy已经实现了类似的功能。

我也知道我可以实现像

这样的方法
def add_element_to_some_array(element):
   some_array.append(element)
   element.some_parent(self)

但我更喜欢像Python中的“属性”那样做。你知道吗?

2 个答案:

答案 0 :(得分:2)

要使您的类行为像数组(或类似dict),您可以覆盖__getitem____setitem__

class HappyArray(object):
  #
  def __getitem__(self, key):
    # We skip the real logic and only demo the effect
    return 'We have an excellent %r for you!' % key
  #
  def __setitem__(self, key, value):
    print('From now on, %r maps to %r' % (key, value))

>>> h = HappyArray()
>>> h[3]
'We have an excellent 3 for you!'
>>> h[3] = 'foo'
From now on, 3 maps to 'foo'

如果您希望对象的多个属性表现出这种行为,则需要多个类似于数组的对象,每个属性对应一个,在主对象的创建时间构建和链接。

答案 1 :(得分:0)

getter属性将返回对该数组的引用。您可以使用它进行数组操作。像这样

class MyClass(object):
    ...        
    @property
    def my_attr(self):
        ...

    @my_attr.setter
    def my_attr(self, value):
        ... 
m = MyClass()
m.my_attr.append(0) # <- array operations like this