+
, -
, and *
. For instance, the +
operator can add numbers, concatenate strings, or merge lists. This flexibility is achieved because Python internally maps operators to special methods (also known as magic methods).For example:5 + 3
performs numeric addition.'Hello' + ' World'
concatenates two strings.[1, 2] + [3, 4]
merges two lists.String
class. By default, the Python compiler doesn’t know how to add a string to an instance of this class. Attempting to do so results in a TypeError
. However, by implementing operator overloading, we can define how the +
operator behaves for our custom class.class String:
def __init__(self, string):
self.string = string
def __repr__(self):
return f'Object: {self.string}'
# Usage
string1 = String('Hello')
print(string1 + ' World')
Output:TypeError: unsupported operand type(s) for +: 'String' and 'str'
class String:
def __init__(self, string):
self.string = string
def __repr__(self):
return f'Object: {self.string}'
def __add__(self, other):
return self.string + other
# Usage
string1 = String('Hello')
print(string1 + ' World')
Output:Hello World
__add__
for +
__sub__
for -
__mul__
for *
__eq__
for ==
Operator | Special Method |
---|---|
+ | __add__ |
- | __sub__ |
* | __mul__ |
/ | __truediv__ |
// | __floordiv__ |
% | __mod__ |
** | __pow__ |
Operator | Special Method |
---|---|
< | __lt__ |
> | __gt__ |
<= | __le__ |
>= | __ge__ |
== | __eq__ |
!= | __ne__ |
Operator | Special Method |
---|---|
+= | __iadd__ |
-= | __isub__ |
*= | __imul__ |
/= | __itruediv__ |
Operator | Special Method |
---|---|
+ | __pos__ |
- | __neg__ |
~ | __invert__ |
class Student:
def __init__(self, marks1, marks2):
self.marks1 = marks1
self.marks2 = marks2
def __add__(self, other):
return Student(self.marks1 + other.marks1, self.marks2 + other.marks2)
def __repr__(self):
return f'Student(marks1={self.marks1}, marks2={self.marks2})'
# Usage
s1 = Student(50, 60)
s2 = Student(30, 40)
s3 = s1 + s2
print(s3)
Output:Student(marks1=80, marks2=100)
class Circle:
def __init__(self, radius):
self.radius = radius
def __lt__(self, other):
return self.radius < other.radius
def __eq__(self, other):
return self.radius == other.radius
# Usage
c1 = Circle(5)
c2 = Circle(10)
print(c1 < c2) # True
print(c1 == c2) # False
is
and and
, cannot.