object .__ reversed__ in Python

Python Methods and Functions

Can be used to implement reverse iteration over an object.

object .__ reversed __ (self)

-> Iterator

self - Link to instance. 

This method is called using reversed () . Should return a new iterator object that allows you to iterate through the container elements in reverse order.

  class MyContainer (object): 

def __init __ (self):
self.storage = ['one',' two', 'three']

def __reversed __ (self):
return iter (self.storage [:: - 1])

container = MyContainer ()
container.storage # ['one',' two', 'three']
list (reversed (container)) # ['three',' two', 'one']


If not implemented, reversed () will use the following sequence protocol methods: __ len__ , __getitem__ . In the case where the specified methods are already defined for the type, it makes sense to define __reversed__ only if it offers a more efficient (optimized) implementation of the pass.