1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class FortranList(list):
def __init__(self, *args, first_index=1):
super().__init__(*args)
self.first_index = first_index
def get_py_idx(self,i):
if isinstance(i, slice):
return slice( i.start-self.first_index,i.stop-self.first_index,i.step)
else :
return i-self.first_index
@property
def last_index(self):
return self.first_index + len(self) - 1
def __getitem__(self, i):
return super().__getitem__(self.get_py_idx(i))
def __setitem__(self, i,val):
super().__setitem__(self.get_py_idx(i),val)
# def __delitem__(self, i):
# raise NotImplementedError
# ### See here to do that : https://stackoverflow.com/questions/20247841/using-delitem-with-a-class-object-rather-than-an-instance-in-python
x=FortranList([5,6,7])
print(x)
print(x[2])
print(x.first_index, x.last_index)
print(len(x))
x.append(8)
x.append(9)
print(x)
print(x[4])
print(x[3:5])
x[2:4]=[12,13]
print(x) |
Partager