Magic methods in Python are special methods that have double underscores (dunder) before and after their names. These methods allow you to define the behavior of objects that belong to a class in a way that integrates seamlessly with Python's built-in features. For instance, these methods can be called automatically in certain situations, such as when an object is created, when it is added to another object, or when it is printed.
Some common magic methods include:
__init__
: Called when an object is instantiated.__str__
: Defines the string representation of an object.__repr__
: Defines the official string representation of an object.__add__
: Defines the behavior of addition for objects.Using magic methods makes your classes more intuitive and Pythonic.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
v1 = Vector(2, 3)
v2 = Vector(4, 5)
result = v1 + v2
print(result) # Output: Vector(6, 8)
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?