Consider the following Python class definition:
class Custom:
def __init__(self, items):
self.items = items
def __getitem__(self, key):
return Custom(items[key])
As an example for what I want to achieve is the following code snippet to print "true"
instead of "false"
:
custom = Custom([1, 2, 3, 4])
view = custom[0:2]
view.items[0] = 0
print(custom.items[0] == 0)
This is, I want to be able to subscript my class (which basically consists of lists only) in a way that makes __getitem__()
return "views" of the instances in the sense that changes to the lists of the views propagate to the lists of the original instance.
I want my class to behave with its saved lists exactly like e.g. numpy
arrays behave with the values it saves. The following prints "true"
:
array = np.array([1, 2, 3, 4])
view = array[0:2]
view[0] = 0
array == 0
How can I achieve this? Thanks!