I'm trying this piece of code expecting that it returns a string of text after reversing with [::-1]
but it is not working.
class meh:
def __init__(self, bla):
self.bla = bla
def __reversed__(self):
return "Reversing!!!! %s" % self.bla[::-1]
a = meh("Reversed successfully!!!!")
print a[::-1]
How to properly call the __reverse__
function?
Example: __gt__
is called with a > 25
, what calls __reverse__
?
Python reversed() method The reversed() method returns the reversed iterator of the given sequence. It is the same as the iter() method but in reverse order. Internally, it calls the __reversed__() method of the sequence class.
The reversed() method computes the reverse of a given sequence object and returns it in the form of a list.
[::-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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With