This tutorial on Operator Overloading in Python will you learn the various aspects of Operator overloading in Python. The Python tutorial will make you understand the concept of Operator Overloading and will demonstrate how to overload operators in Python with classic examples. You will get to know the concept deeper with a hands-on demo.
2. What’s in it for you?
How to overload the operators in
Python?
What is Operator Overloading?
3. What is Operator Overloading?
Python operators work for built-in classes in a predefined
operational way. But the same operator behaves
differently for objects of different classes
For example, the + operator will perform arithmetic
addition on two numbers, merge two lists, or
concatenate two strings
This feature in Python that allows the same operator to
have different meanings according to the context is
called operator overloading
8 + 7
Operands
Operator
4. How to overload the operators in Python?
Object 1
B1=batsman(66, 78)
Class Batsman
Object 2
B2=batsman(23, 59)
Consider that we have two objects B1 and B2 of a class Batsman. We
must add both objects with a binary ‘+’ operator
It will throw an error
because the compiler
doesn’t know how to
add two objects. Here,
we will define a method
for an operator and that
process is called
operator overloading
5. How to overload the operators in Python?
We can overload all defined
operators. Python provides some
special or magic function that
is automatically invoked when
associated with that operator to
perform operator overloading
• __add__()
• __sub__()
• __mul__()
• __div__()
• __gt__()
• __lt__()
These are some of the
magic methods
6. How to overload the operators in Python?
For example, when we use
the + operator, the magic
method __add__ is
automatically invoked in
which the operation for the
+ operator is defined. Here
we will overload the +
operator to add the scores
of batsman
Output
7. INDIA
Simplilearn Solutions Pvt. Limited
#53/1C, 24th Main, 2nd Sector
HSR Layout, Bangalore 560102
Phone: +91 8069999471
UNITED STATES
Simplilearn Solutions Pvt. Limited
801 Corporate Center Drive, Suite 138
Raleigh, NC 27607
Phone: (919) 205-5565
UNITED STATES
Simplilearn Solutions Pvt. Limited
201 Spear Street, Suite 1100
San Francisco, CA 94105
Phone: (415) 741-3319
Join us to learn more!