Language

Classes & Objects · Lesson 28 of 56

Operator Overloading

Source: 8-Class And Objects/8.7-OperatorOverloading.ipynb

Start here — no coding background needed

What you will learn

Teach operators like + what to do for your own types.

In simple words

Rare for beginners — skim now; revisit when building custom math types.

Group data and actions together — used in bigger apps; go slow, use analogies.

Easy example — try this first

Easy example — run this first. Change values and press Run again.

Python

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference notes (from full bootcamp)

Optional — deeper detail for when you are ready

Operator Overloading

Operator overloading allows you to define the behavior of operators (+, -, *, etc.) for custom objects. You achieve this by overriding specific magic methods in your class.

Reference example
Python
Output
Expected (from notebook):
'\n__add__(self, other): Adds two objects using the + operator.\n__sub__(self, other): Subtracts two objects using the - operator.\n__mul__(self, other): Multiplies two objects using the * operator.\n__truediv__(self, other): Divides two objects using the / operator.\n__eq__(self, other): Checks if two objects are equal using the == operator.\n__lt__(self, other): Checks if one object is less than another using the < operator.\n\n'

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python
Output
Expected (from notebook):
Vector(6, 8)
Vector(-2, -2)
Vector(6, 9)

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Practice test — try yourself

Write code, press Check. Wrong answer shows the correct code to copy & run.

You learned "Operator Overloading". Use print() to show: Done: Operator Overloading

Hint: Use one print() with the exact text.

Python