Welcome to the “Special Methods” tutorial!
Overview
Special (dunder) methods let you customize built-in behaviors like printing, addition, iteration, etc.
Common Special Methods
__init__
: constructor__str__
: human-readable representation__repr__
: unambiguous representation__add__
,__len__
,__eq__
, etc.
Example
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
Key Takeaways
- Override dunder methods to integrate with Python syntax.
__str__
vs__repr__
: user vs developer representation.
Happy coding!
Comments
Post a Comment