Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator
Operator overloading is a feature in Python that allows operators, such as +, -, *, /, %, ==, >, <, and others, to be used with objects of user-defined classes. This means that the behavior of operators can be customized for objects of a specific class, allowing for more intuitive and natural syntax.
In Python, operator overloading is achieved by defining special methods in a class that correspond to the desired operator. For example, to overload the + operator, the add() method needs to be defined in the class. When an object of that class is used with the + operator, Python will call the add() method with the object and the value being added as arguments.
Here is an example of operator overloading in Python:
class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) p1 = Point(1, 2) p2 = Point(3, 4) p3 = p1 + p2 print(p3.x, p3.y) # output: 4 6
In this example, the Point class overloads the + operator by defining the add() method, which returns a new Point object with the x and y values of the two points added together. The result is a new Point object representing the sum of the two points.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.