__reversed__ magic method in Python with examples
Hello everyone, in this post, we will talk about the __reversed__ magic method in Python with examples. Like other magic methods, this special method also begins and ends with a pair of underscores. We will see how we can use this special __reversed__ method in our Python Program further in this tutorial.
__reversed__ magic method in Python
What are magic methods?
Yes! what are these little so-called magic methods? Well, in truth, there’s nothing magical about these functions. These special methods in Python are just used sometimes to emulate the behavior of some built-in types. If you wish to have more knowledge about these, you can spend some time on this page: Underscore Methods in Python.
The __reversed__ magic method is used to emulate the behavior of the reversed() function. This function returns an iterator using which we can access all the elements in a sequence.
class Numbers: def __init__(self): self.numbers = [1, 2, 3, 4, 5] def __reversed__(self): for number in self.numbers[::-1]: yield number numbers_obj = Numbers() for number in reversed(numbers_obj): print(number)
5 4 3 2 1
When we create the class numbers, we use __init__ special method to create an object which is initialized as a list of numbers from 1 to 5. The magic method __reversed__ create an iterator for the object which can iterate through the elements of the list in the reverse order. Then we use the reverse() method with the object to print the elements in the reverse order.
Also read: Reverse each word in a sentence in Python
Leave a Reply