🎓 All Courses | 📚 Python Programming Syllabus

📋 Study this course on TaskLoco
#python-programming#oop#dunder-methods

Dunder Methods — Python's Magic

Dunder (double underscore) methods let your classes work with Python's built-in operators.


class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

    def __str__(self):
        return f"({self.x}, {self.y})"

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __len__(self):
        return 2

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __lt__(self, other):
        return (self.x**2 + self.y**2) < (other.x**2 + other.y**2)

v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2      # uses __add__
print(v3)         # uses __str__
len(v1)           # uses __len__

Key dunders: __init__, __str__, __repr__, __len__, __add__, __eq__, __lt__, __contains__, __getitem__, __call__


YouTube • Top 10
Python Programming: Object-Oriented — Dunder Methods
Tap to Watch ›
📸
Google Images • Top 10
Python Programming: Object-Oriented — Dunder Methods
Tap to View ›

Reference:

Wikipedia: Python

image for linkhttps://en.wikipedia.org/wiki/Python_(programming_language)

📚 Python Programming — Full Course Syllabus
📋 Study this course on TaskLoco

TaskLoco™ — The Sticky Note GOAT