The [ ]
is called indexing or slicing (or sometimes array/sequence/mapping-like access). The x[idx] = val
is called index or slice assigment.
The methods that are responsible how the instance acts when indexed or sliced are:
__getitem__
,
__setitem__
and
__delitem__
.
- (In Python-2.x there is also
__getslice__
, ... but these are deprecated since python 2.0 - if you don't inherit from a class that uses these you shouldn't need those)
For example (missing any actual implementation, just some print
s):
class Something(object):
def __getitem__(self, item):
print('in getitem')
def __setitem__(self, item, newvalue):
print('in setitem')
def __delitem__(self, item):
print('in delitem')
For example:
>>> sth = Something()
>>> sth[10]
in getitem
>>> sth[10] = 100
in setitem
>>> del sth[10]
in delitem