我有一个自定义
__setitem__()
功能。
class Myclass:
array = [[[1]*3]]
def __setitem__(self, idcs, other):
# do something
array[idcs] = other
return 2
我想做这样的事情:
x = Myclass()
other = [1, 2, 3]
z = x.__setitem__([0:1, 0:1, 0:], other) # change the given range of x and assign the return value to
但它不起作用并返回无效语法错误。我希望结果是这样的:
z == 2
x.array == [[[1, 2, 3]]]
我该怎么办?
我根据您的问题整理了一些用法,但请考虑以下几点:
你的
array
非常令人费解/复杂,你真的需要它吗?
__setitem__
不应该返回值,只能设置它
__getitem__
负责返回值
提供的示例是最终使用串联
__setitem__ / __getitem__
和slice
的非常基本的示例,数据结构也是一个简单的list
如果您像这样更改数据结构,就会出现一些微妙之处,如
.multiple_assing()
所示
from typing import Iterable
class CustomContainer:
def __init__(self):
# dummy data
self._data = [1,2,3,4,5,6,7,8,9]
def __setitem__(self, key, value):
# valid for iterables only !
self._data[key] = value
def __getitem__(self, key):
return self._data[key]
def multiple_assing(self, slices: list[tuple], value:Iterable):
for sl in slices:
self[slice(*sl)] = value
def __str__(self):
return str(self._data)
if __name__ == "__main__":
cc = CustomContainer()
print(cc)
# subtlety by the usage of such change
# start --> [1, 2, 3, 4, 5, 6, 7, 8, 9]
# first change --> x x x x
# changed to --> [10, 4, 5, 6, 7, 8, 9]
# second change --> x x x x
# changed to --> [10, 4, 5, 10]
cc.multiple_assing([(0,3), (3,None,None)], [10])
print(cc)
# final --> [10, 4, 5, 10]