Skip to main content
 首页 » 编程设计

用于数组操作的 Python 属性

2024年10月25日14oomusou

当使用 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 中的“属性”那样来做……你知道什么方法吗?

请您参考如下方法:

为了让你的类表现得像数组(或字典),你可以覆盖 __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' 

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