Python __reverse__ magic method
[::-1]
is a slice. object.__reversed__()
is instead used by the reversed()
function, and is only applicable to sequences (objects that provide both a __len__
and a __getitem__
method).
If you don't supply __reversed__
, the function uses those __len__
and __getitem__
methods to access indices in reverse. __reversed__
must itself return an iterator:
class Reversable(object):
def __init__(self, seq):
self.seq = seq
def __len__(self):
return len(self.seq)
def __getitem__(self, item):
return self.seq[item]
def __reversed__(self):
for elem in 'Reversing: ' + self.seq[::-1]:
yield elem
Demo:
>>> class Reversable(object):
... def __init__(self, seq):
... self.seq = seq
... def __len__(self):
... return len(self.seq)
... def __getitem__(self, item):
... return self.seq[item]
... def __reversed__(self):
... for elem in 'Reversing: ' + self.seq[::-1]:
... yield elem
...
>>> r = Reversable('Foo bar baz!')
>>> list(r)
['F', 'o', 'o', ' ', 'b', 'a', 'r', ' ', 'b', 'a', 'z', '!']
>>> list(reversed(r))
['R', 'e', 'v', 'e', 'r', 's', 'i', 'n', 'g', ':', ' ', '!', 'z', 'a', 'b', ' ', 'r', 'a', 'b', ' ', 'o', 'o', 'F']