__setitem__ / __getitem__ / __delitem__
Example 1:
class CustomList(object):
values = []
def __init__(self, nums=0):
self.values = [0] * nums
def __setitem__(self, idx, val):
self.values[idx] = val
def __getitem__(self, idx):
return "Index {}, value {}".format(idx, self.values[idx])
def __str__(self):
return str(self.values)
obj = CustomList(12)
obj[0] = 1
print(obj[0])
print(obj)
Example 2:
class CustomList(object):
values = []
def __init__(self, nums=0):
self.values = [0] * nums
def __setitem__(self, idx, val):
self.values[idx] = val
def __getitem__(self, idx):
return "Index {}, value {}".format(idx, self.values[idx])
def __delitem__(self, idx):
del self.values[idx]
def __str__(self):
return str(self.values)
obj = CustomList(12)
obj[0] = 1
obj[1] = 2
obj[2] = 3
print(obj[0])
print(obj)
del obj[0]
print(obj)