Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python __reverse__ magic method

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__?

like image 867
Filipe Teixeira Avatar asked Dec 24 '14 15:12

Filipe Teixeira


People also ask

What is __ reversed __ in Python?

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.

What does reversed () do?

The reversed() method computes the reverse of a given sequence object and returns it in the form of a list.


Video Answer


1 Answers

[::-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']
like image 191
Martijn Pieters Avatar answered Sep 23 '22 12:09

Martijn Pieters