Free Interactive Python Course

Python Tutorial — Learn Python Step by Step

Key takeaway: Master Python programming from scratch — variables, loops, functions, OOP, file handling, and libraries — with clear human-readable explanations and runnable code examples.

50+ Structured Lessons
Runnable Code Examples
100% Free No Registration
Updated October 2026

Python Operator Overloading

Operator overloading lets you define how operators like +, -, ==, and < behave with your custom classes by implementing special dunder methods.

Arithmetic Operators

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

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

    def __sub__(self, other):
        """v1 - v2"""
        return Vector(self.x - other.x, self.y - other.y)

    def __mul__(self, scalar):
        """v * number (scalar multiplication)"""
        return Vector(self.x * scalar, self.y * scalar)

    def __rmul__(self, scalar):
        """number * v (reverse multiplication)"""
        return self.__mul__(scalar)

    def __neg__(self):
        """-v (unary negation)"""
        return Vector(-self.x, -self.y)

    def __abs__(self):
        """abs(v) — magnitude"""
        return (self.x**2 + self.y**2) ** 0.5

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

v1 = Vector(3, 4)
v2 = Vector(1, 2)

print(v1 + v2)    # Vector(4, 6)
print(v1 - v2)    # Vector(2, 2)
print(v1 * 3)     # Vector(9, 12)
print(2 * v1)     # Vector(6, 8) — uses __rmul__
print(-v1)        # Vector(-3, -4)
print(abs(v1))    # 5.0

Comparison Operators

from functools import total_ordering

@total_ordering  # auto-generates <=, >, >= from __eq__ and __lt__
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def __eq__(self, other):
        """=="""
        return self.celsius == other.celsius

    def __lt__(self, other):
        """<"""
        return self.celsius < other.celsius

    def __repr__(self):
        return f"{self.celsius}°C"

t1 = Temperature(20)
t2 = Temperature(30)
t3 = Temperature(20)

print(t1 == t3)  # True
print(t1 < t2)   # True
print(t2 >= t1)  # True (auto-generated by @total_ordering)

# Now sorting works!
temps = [Temperature(30), Temperature(10), Temperature(25)]
print(sorted(temps))  # [10°C, 25°C, 30°C]

Container Operators

class Playlist:
    def __init__(self, name):
        self.name = name
        self._songs = []

    def __len__(self):
        """len(playlist)"""
        return len(self._songs)

    def __getitem__(self, index):
        """playlist[i] and slicing"""
        return self._songs[index]

    def __setitem__(self, index, value):
        """playlist[i] = song"""
        self._songs[index] = value

    def __contains__(self, song):
        """song in playlist"""
        return song in self._songs

    def __iter__(self):
        """for song in playlist"""
        return iter(self._songs)

    def __iadd__(self, song):
        """playlist += song"""
        self._songs.append(song)
        return self

    def __repr__(self):
        return f"Playlist('{self.name}', {len(self)} songs)"

playlist = Playlist("Road Trip")
playlist += "Hotel California"
playlist += "Bohemian Rhapsody"
playlist += "Stairway to Heaven"

print(len(playlist))                    # 3
print(playlist[0])                      # Hotel California
print("Bohemian Rhapsody" in playlist)  # True
print(playlist[1:])                     # [Bohemian..., Stairway...]

for song in playlist:
    print(f"  ♪ {song}")

Operator Reference Table

OperatorMethodReverse
+__add____radd__
-__sub____rsub__
*__mul____rmul__
/__truediv____rtruediv__
==__eq__—
<__lt____gt__
[]__getitem__—
len()__len__—
in__contains__—
str()__str__—
  • Implement __add__, __sub__, etc. to make your objects work with +, - operators.
  • Use @total_ordering to only define __eq__ and __lt__ — the rest auto-generate.
  • Implement __rmul__ (reverse) so both obj * 3 and 3 * obj work.
  • Implement __getitem__ and __len__ to make objects behave like collections.
  • Overloaded operators should return new objects — avoid modifying self (except __iadd__).

Python Programming Tutorial — Learn Python in a practical, step-by-step way. According to the official Python documentation, Python emphasizes code readability and simplicity, making it ideal for beginners.

Related tools: Python Online Compiler | Python Examples | JavaScript Tutorial | Java Tutorial

Python Career & Learning Guide

Python is the world's most popular programming language for beginners, data science, AI/ML, web development, and automation. This tutorial teaches Python step-by-step with clear explanations and runnable code examples in our free Python Compiler.

Why Learn Python in 2026?

  • #1 Most Popular Language: Ranked first on TIOBE, Stack Overflow, and GitHub.
  • AI and Data Science: The primary language for machine learning (TensorFlow, PyTorch, scikit-learn) and data analysis (Pandas, NumPy).
  • Web Development: Django and Flask power scalable backends at companies like Instagram and Spotify.
  • Automation & Scripting: Automate files, emails, web scraping, and data processing in minutes.

Python vs Other Languages

FeaturePythonJavaJavaScriptC++
SyntaxVery clean, readableVerboseModerateComplex
TypingDynamic, strongStatic, strongDynamic, weakStatic, strong
Best ForAI/ML, Data, WebEnterprise, AndroidWeb Frontend/BackendSystems, Games
Learning Time2–4 weeks basics4–6 weeks basics3–4 weeks basics8–12 weeks basics

Frequently Asked Questions

Do I need prior programming experience to learn Python?

No! Python is specifically designed to be beginner-friendly. This tutorial starts from zero and builds up gradually.

Which Python version should I use?

Python 3.10+ is recommended. All examples in this tutorial use Python 3 syntax.

Is this Python tutorial completely free?

Yes, 100% free with no registration or sign-up required. Access all lessons and code examples anytime.