In Python, we sometimes see method names with
__ around, such as the
__init__ method that every Class has. These methods are “dunder” methods (“dunder” stands for “double under” or “double underscore”). Dunder methods in Python are used for operator overloading and customizing behavior of other functions.
Sometimes dunder methods are also called “magic methods” because they are usually called by Python under the hood. But they are not really magical, you can define dunder methods to customize the behavior of your own classes.
Examples of Dunder Methods
In the following example, we can see three dunder methods:
__init__method: is called to initialize the class
__str__method: is called when converting the object to a human-readable string
__repr__method: is called when converting the object to a developer-readable string
1 2 3 4 5 6 7 8 9
In Python, many dunder methods are implemented and used for operations such as arithmetic operators, comparison operators, truthiness, etc. The following are a few examples:
x < y:
x <= y:
x > y:
x >= y:
x == y:
x != y:
If you know about Bash shell, you may notice the name of these dunder methods are very similar to the operators in Bash.
Use Dunder Methods to Customize Class Behaviors
Dunder methods provide a way for our class to customize operators and other built-in Python behavior for our objects. In the following two examples, I’ll use dunder methods to overload arithmetic operators, and implement a dictionary that can be used with both attribute and item syntax.
Example 1: Overload Arithmetic Operators
is_callable function to check if an object type is callable.
This can be done by calling object’s
1 2 3 4 5 6
1 2 3 4 5 6 7 8 9 10
Example 2: Class EasyDict
EasyDict class that can be used with both attribute and item syntax.
This can be done by implementing
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9
More dunder methods can be found in Python documents: operator – Standard operators as functions (Python 3.6.3)