Python has a bunch of methods called “dunder methods” or “magic methods” that give superpower to our classes. In this article, we will talk about __gt__()
method of Python.
Suppose we have a class BankAccount that represents bank accounts and consists of three attributes, holder_name, accound_id, balance as following:
Then we create a list of BankAccount objects and print each element using the method __str__()
we implemented in the class above.
Suppose we want to print all the accounts of the list, but this time in ascending order. So we try to execute the following command.
💡 Learn how to use the zip method to convert lists into dictionaries in Python:
How to Use the Zip Method to Convert Lists into Dictionaries
👉 To read more such acrticles, sign up for free on Differ.
But, as we can see instead of getting an ordered output of the bank accounts, we get a TypeError, which informs us that the comparison with symbol < not supported between instances of our class. As we mentioned in the article about __eq__()
magic method, this is because for the objects of the classes defined by the user we have to determine the way in which they will be compared with each other. Python has no idea how to compare two objects of class BankAccount. For this reason, python has a number of methods called “magic” or “dunder” methods which gives our classes extra functionality. So, to define how to compare the objects, we can use the magic method __gt__()
(means greater than). In our example, we want to compare our objects based on attribute balance. So we implement the __gt__()
as follows:
After that, we try again to execute the following command:
As we execute the script we notice that we have the expected output. We will try now to print the list of accounts but this time in descending order. So, we execute the following script:
We notice that we get the expected output. That’s because implementing the method __gt__()
, we define the behaviour of the greater-than operator, so python knows how to define behaviour of the less-than operator <.
Conclusion
In this article, we talked about __gt__()
magic method. This method is necessary if we want to sort objects of our class. Remember that, except __gt__()
and __eg__()
we discussed in my last article, there are a lot of other magic methods that make our classes powerful. Thanks for reading and keep learning.