Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
数组操作的Python属性_Python_Python 3.x - Fatal编程技术网

数组操作的Python属性

数组操作的Python属性,python,python-3.x,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的引用。我知

使用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中的“属性”一样进行操作。。你知道怎么做吗

要使类的行为类似于数组(或dict),可以重写和
\uuuuu setitem\uuuu

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'

如果希望对象的多个属性显示这种行为,则需要多个类似数组的对象,每个属性一个,在主对象创建时构造并链接。

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
类MyClass(对象):
...        
@财产
定义我的属性(自我):
...
@我的属性设置器
定义我的属性(自我,值):
... 
m=MyClass()

m、 我的属性附加(0)#谢谢,我希望得到更多类似属性的解决方案,但我想这是不可能的。。我将投票表决你的答案=)