Skip to main content

Python Tutorial 8.2 - Special Methods

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