Magic methods
Small list
Magic methods are special methods that can be implemented, and then be used with standard Python constructions like +
, len(..)
, print(...)
, etc.
Python constructions | Real thing happening with magic methods |
---|---|
1+2 | (1).__add__(2) |
2 * 3 | (2).__mul__(3) |
len(a) | a.__len__() |
print(a) | print(a.__repr__) |
Full list here: https://docs.python.org/3/reference/datamodel.html#specialnames
Example
from dataclasses import dataclass
@dataclass
class Vector2D:
"""Class for representing a point in 2D."""
x: float
y: float
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
print(Vector2D(2, 3) + Vector2D(10, 40))
Vector2D(x=12, y=43)
There are libraries to manipulate numbers with units, e.g. https://pypi.org/project/Pint/