Python Operator Overloading

1) __str__ Overload

Create a Person class with name and age, override __str__ so printing the object shows:

name – age

2) __add__ for Numbers

Define a class NumberObj holding an integer. Implement __add__ so:

NumberObj(3) + NumberObj(4) β†’ NumberObj(7)

3) __eq__ Comparison

Create a class Point with x and y. Overload __eq__ so two points are equal if both coordinates match.


4) __lt__ / <

Extend Point so:

Point(1,2) < Point(3,4)

compares based on sum of coordinates.


5) __len__ Overload

Define a class MyList storing a list internally. Overload __len__ to return its length.


6) __getitem__

In MyList, support indexing:

returns first element.


7) __setitem__

In MyList, allow assigning:


8) __contains__ for in

Overload so:

works, based on internal list.


9) __sub__ Overload

Implement subtraction for NumberObj:


10) __mul__ for Scaling

Create class Vector2D(x,y) and overload * to scale:


11) __add__ for Strings

Define a class wrapping a string so + joins text.


12) Polymorphic __add__

Make __add__ work when adding object + raw number (not object).


13) __repr__ Overload

Add __repr__ to a class so that when the object is printed in a list, it looks readable.


14) __neg__ for Unary -

In class NumberObj, overload unary minus to flip sign.


15) __gt__ / >

Compare two durations (e.g., hours attribute) using >.


16) Overload ==/!= Together

Create a class representing a book; consider two books equal if title and author match.


17) Custom Addition for Composite

Define class Student with grades list; overload + to merge grade lists.


18) __add__ & __iadd__

Implement both __add__ and __iadd__ so:

updates internal contents.


19) Overload Comparison Chain

Implement both < and <= consistently for a class wrapping an integer.


20) __mul__ for Repeated Objects

In a custom string wrapper class, overload * so:

repeats the text.


🧠 Concepts Practiced

Operator
Special Method

Addition

__add__

Subtraction

__sub__

Multiplication

__mul__

Length

__len__

Equality

__eq__

Greater / Less

__gt__, __lt__

Index access

__getitem__, __setitem__

Contains (in)

__contains__

String rep

__str__, __repr__

Unary negation

__neg__


πŸ“Œ Example Starter

Assignment 2: __add__ for Numbers


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated