- Python Snacks
- Posts
- 4 types of Python dunder (magic) methods you should know
4 types of Python dunder (magic) methods you should know
Dunder methods can change your python game significantly if you know how to leverage them correctly.
Have you ever noticed those special methods in Python surrounded by double underscores, such as __init__ and __str__. These are double underscore (“dunder”) methods that makes Python feel so smooth and intuitive.
Dunder methods (AKA magic methods) are special functions that Python calls automatically in certain situations. These situations can entail:
Creating an object (__init__)
Comparing 2 objects (__eq__, __lt__, __ge__, etc)
Printing an object (__str__)
In fact, I wrote a few articles about a few double underscore (“dunder”) methods:
TLDR: They let you customize how your objects behave without writing a ton of extra code.
4 Types of Dunder Methods You Should Know
Object Instantiation (__init__)
If you come from a language such as Java, you’ll generally create objects using a constructor. Python does not have constructors, but they have a method that gets called upon initializing an object. Take this sample code:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
point = Point(2, 3)
print(point.x) # Output: 2
We don’t need to have the __init__ method in order for our object to be created, but it does allow us to set attributes of the object straight out of the gates. In this example, we are able to set the x and y coordinates as soon as we create the object.
Type Conversions
If you’ve ever tried to convert a float to an int, you may have done something such as float(number). Python has dunder methods that allow you to do this:
Method | Return Type |
---|---|
__bool__ | Boolean |
__str__ | String |
__int__ | Integer |
__float__ | Float |
__bytes__ | Bytes |
__complex__ | Complex |
A good example of this is a Temperature class:
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def __int__(self):
return int(self.celsius)
def __float__(self):
return float(self.celsius)
def __str__(self):
return f"{self.celsius}°C"
def __repr__(self):
return f"Temperature({self.celsius})"
Arithmetic Operators
If you’re in a situation where you find yourself doing some kind of arithmetic on Python objects, these dunder methods allow you to customize the behavior of how the objects get added, subtracted, etc.
Method | Operator | Description |
---|---|---|
__add__ | + | Addition |
__sub__ | - | Subtraction |
__mul__ | * | Multiplication |
__truediv__ | / | Division |
__floordiv__ | // | Floor Division |
__mod__ | % | Modulus |
__pow__ | ** | Exponentation |
__matmul__ | @ | Matrix Multiplication |
So, for instance, we may have a Vector class:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __rmul__(self, scalar):
return self.__mul__(scalar)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
And if we were to implement this:
# Example Usage
v1 = Vector(1, 2)
v2 = Vector(3, 4)
# Basic Operations
print(v1 + v2) # Vector(4, 6)
print(v2 - v1) # Vector(2, 2)
print(v1 * 2) # Vector(2, 4)
print(3 * v2) # Vector(9, 12)
Comparison Operators
If you need to compare your objects, Python provides comparison operator dunder methods:
Method | Operator | Description |
---|---|---|
__eq__ | == | Equal to |
__ne__ | != | Not equal to |
__lt__ | < | Less than |
__gt__ | > | Greater than |
__le__ | <= | Less than or equal to |
__lt__ | >= | Greater than or equal to |
In your class, it may look as such:
class Comparison:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __lt__(self, other):
return self.value < other.value
# ... and so forth
That’s all for today - happy coding!
📧 Join the Python Snacks Newsletter! 🐍
Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:
Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.
Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.
Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.
You can unsubscribe at any time.
Interested in starting a newsletter or a blog?
Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.
If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.
This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.
Reply