- Operator Overloading in Python
- Python3
- Python Оператор AND
- Логический оператор И
- Перегрузка логического оператора
- Побитовый оператор И
- Побитовая перегрузка оператора
- Порядок оценки
- Operator Overloading in Python
- Example: Depicting different use of basic arithmetic operators
- How to overload an operator in python?
- Special Functions in Python
- Magic Methods for Binary Operators in Python
- Magic Methods for Comparison Operators in Python
- Magic Methods for Assignment Operators in Python
- Magic Methods for Unary Operators
- Example: Overloading binary + operator in Python
- Example: Overloading comparison operators in Python
- Example: Sample Operator Overloading Program
- References
- Operator Overloading in Python
- Why operator overloading?
- How to perform operator overloading?
Operator Overloading in Python
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 Overloading.
Python3
3 GeeksFor 12 GeeksGeeksGeeksGeeks
How to overload the operators in Python?
Consider that we have two objects which are a physical representation of a class (user-defined data type) and we have to add two objects with binary ‘+’ operator it throws an error, because compiler don’t know how to add two objects. So we define a method for an operator and that process is called operator overloading. We can overload all existing operators but we can’t create a new operator. To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator. For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined.
Overloading binary + operator in Python:
When we use an operator on user-defined data types then automatically a special function or magic function associated with that operator is invoked. Changing the behavior of operator is as simple as changing the behavior of a method or function. You define methods in your class and operators work according to that behavior defined in methods. When we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined. Thereby changing this magic method’s code, we can give extra meaning to the + operator.
How Does the Operator Overloading Actually work?
Whenever you change the behavior of the existing operator through operator overloading, you have to redefine the special function that is invoked automatically when the operator is used with the objects.
Python Оператор AND
Операторы в основном используются для выполнения операций с данными, которыми нужно управлять. Существуют различные типы операторов, например логические, побитовые, арифметические и т. д.
В Python есть два типа операторов AND:
Логический оператор И
Логический оператор И работает с логическими значениями и приводит к истинному или ложному результату в зависимости от условия. Оператор and возвращает True, если оба операнда имеют значение True, в противном случае он возвращает False.
num1 = int(input('Enter first number:\n')) num2 = int(input('Enter second number:\n')) if num1 > num2 and num1 < 10: print('True') elif num1 < 0 and num2 < 0: print('Both the numbers are negative.') else: print('False')
Введите первое число: 9 Введите второе число: 5 Верно
Перегрузка логического оператора
Логические операторы Python работают с логическими значениями. По умолчанию логическое значение объекта — True. Если объект — None или False, то значение — False. Мы можем предоставить реализацию __bool __() для изменения логических значений объекта по умолчанию.
class Data: def __init__(self, i): self.id = i def __bool__(self): return self.id % 2 == 0 d1 = Data(6) d2 = Data(4) print(bool(Data(3)) and bool(Data(4))) # False
Приведенный выше фрагмент кода напечатает False, потому что логическое значение Data (3) — False.
Если мы удалим реализацию функции __bool __(), оба значения объектов данных будут True и будут напечатаны True.
Побитовый оператор И
Побитовые операторы работают с битами. Он возвращает 1, когда оба бита операндов равны 1, иначе он возвращает 0 (ноль).
ab = 0110 0100 = 0100 = 4 (десятичный)
Побитовая перегрузка оператора
Существуют различные определенные методы перегрузки побитовых операторов в Python.
Побитовый оператор | Syntax |
---|---|
& | __and __ (self, other) |
| | __или __ (self, other) |
^ | __xor __ (self, other) |
~ | __invert __ (self) |
__lshift __ (self, other) | |
>> | __rshift __ (self, other) |
class Operate(): def __init__(self, x): self.x = x def __and__(self, res): print("Bitwise AND operator overloading Example") if isinstance(res, Operate): return self.x res.x else: raise ValueError("Must belong to Operate Class") if __name__ == "__main__": a = Operate(6) b = Operate(4) print(ab)
Bitwise AND operator overloading Example 4
Порядок оценки
Выполнение операндов через операторы происходит left to right .
def evaluate(n): print("Function called for operand:", n) return True if n > 0 else False x = evaluate y = evaluate z = evaluate if x(-1) or y(5) and z(10): print("One of the numbers is positive.")
Функция, вызываемая для операнда: 5 Функция, вызываемая для операнда: 10 Одно из чисел положительное.
Operator Overloading in Python
Operator Overloading is the phenomenon of giving alternate/different meaning to an action performed by an operator beyond their predefined operational function. Operator overloading is also called Operator Ad-hoc Polymorphism.
Python operators work for built-in classes. But the same operator expresses differently with different types. For example, The + operator will perform arithmetic addition on two numbers, merge two lists and concatenate two strings. Python allows the same operator to have different meanings according to the referring context.
Example: Depicting different use of basic arithmetic operators
# Program to show use of # + operator for different purposes. print(5 + 5) # concatenate two strings print("Safa"+"Mulani") # Product two numbers print(10 * 10) # Repeat the String print("Safa"*4)
10 SafaMulani 100 SafaSafaSafaSafa
How to overload an operator in python?
To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator. For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined.
Special Functions in Python
Global functions that begin with double underscore __ are called special functions in Python. It’s because they are not ordinary. The __init__() function which we usually define and resemble as a constructor is one of them. It gets called every time we create a new object of that class.
Magic Methods for Binary Operators in Python
OPERATOR | MAGIC METHOD |
---|---|
+ | __add__(self, other) |
– | __sub__(self, other) |
* | __mul__(self, other) |
/ | __truediv__(self, other) |
// | __floordiv__(self, other) |
% | __mod__(self, other) |
** | __pow__(self, other) |
Magic Methods for Comparison Operators in Python
OPERATOR | MAGIC METHOD |
---|---|
__lt__(self, other) | |
> | __gt__(self, other) |
__le__(self, other) | |
>= | __ge__(self, other) |
== | __eq__(self, other) |
!= | __ne__(self, other) |
Magic Methods for Assignment Operators in Python
OPERATOR | MAGIC METHOD |
---|---|
-= | __isub__(self, other) |
+= | __iadd__(self, other) |
*= | __imul__(self, other) |
/= | __idiv__(self, other) |
//= | __ifloordiv__(self, other) |
%= | __imod__(self, other) |
**= | __ipow__(self, other) |
Magic Methods for Unary Operators
OPERATOR | MAGIC METHOD |
---|---|
– | __neg__(self, other) |
+ | __pos__(self, other) |
~ | __invert__(self, other) |
Example: Overloading binary + operator in Python
When we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined. Hence by changing the magic method’s code, we can give alternative meaning to the + operator.
# Program to overload an binary + operator class X: def __init__(self, x): self.x = x # adding two objects def __add__(self, y): return self.x + y.x ob1 = X(5) ob2 = X(5) ob3 = X("Safa") ob4 = X("Mulani") print(ob1 + ob2) # simple addition of objects print(ob3 + ob4) # concatenation of strings through object addition
Example: Overloading comparison operators in Python
class X: def __init__(self, x): self.x = x def __lt__(self, other): # Overloading < operator if(self.x ob1 is less than ob2 Not equalExample: Sample Operator Overloading Program
class Animal: def __init__(self, age): self.__age = age def setage(self, age): self.__age = age def getage(self): return self.__age def __add__(self, predict): return Animal( self.__age + predict.__age ) def __gt__(self, predict): return self.__age > predict.__age def __lt__(self, predict): return self.__age < predict.__age def __str__(self): return "Animal with original age " + str(self.__age) c1 = Animal(5) print(c1.getage()) c2 = Animal(5) print(c2.getage()) c3 = c1 + c2 print(c3.getage()) print( c3 >c2) print( c1 < c2) print(c3)5 5 10 True False Animal with original age 10References
Operator Overloading in Python
- It provides reusability, instead of writing multiple methods that differ slightly we can simply write one method and overload it.
- It also improves code clarity and eliminates complexity.
- It makes code concise and simple to understand.
Why operator overloading?
Consider two objects of a user-defined data type, now if we try to multiply both with an operator * the compiler will throw an error because the compiler doesn’t know how to multiply the operands.
For example, let's take a case where we have defined our own Coordinates class with two attributes x and y. Now, objects of this class would represent different points and using + directly on these points (objects) would give us an error. Let's look at the example to understand this.
class Coordinates: def __init__(self, x, y): self.x = x self.y = y p1 = Coordinates(1, 2) p2 = Coordinates(2, 3) print(p1+p2) Traceback (most recent call last): File "", line 9, in
TypeError: unsupported operand type(s) for +: 'Coordinates' and 'Coordinates'.
Here, the compiler is unable to understand what p1+p2 means.
To resolve this problem we can define a method to overload the + operator to change its functionality as per our needs.
How to perform operator overloading?
To perform the operator overloading, python provides some special function or magic function which automatically gets invoked when associated with that particular operator.
For example, when we use * operator, the magic method __mul__ is automatically invoked in which the operation for * operator is already defined.
class Coordinates: def __init__(self, a,b): self.a = a self.b=b # adding two objects def __add__(self, o): a=self.a+o.a b=self.b+o.b s3=Coordinates(a,b) return s3 p1=Coordinates(30,40) p2=Coordinates(70,80) s3=p1+p2 print(s3.a) #sum of the x coordinates print(s3.b) #sum of the y coordinatesHere we have defined the __add()__ method and passed the Coordinates object and got the sum of the coordinates as the result.
This is how we can define the magic methods and can also change their behavior according to our needs.
In python whenever we use ‘+’ operator, python directly call the method that is associated to it i.e. __add()__ method.
Python arithmetic on two complex numbers :
class complex: def __init__(self, real, imag): self.real = real self.imag = imag def __add__(self, other): return complex(self.real+other.real, self.imag+other.imag) def __sub__(self, other): return complex(self.real-other.real, self.imag-other.imag) def __str__(self): return str(round(self.real,2))+('+' if self.imag>=0 else '-')+str(round(abs(self.imag),2))+'i' print("Enter real and imaginary part of complex No - 1(separeated by space)") A = complex(*map(float,input().split())) #the numbers are split by the space between them and passed to the function. * is used to pass multiple values at the same time. print("Enter real and imaginary part of complex No - 2(separeated by space)" ) B = complex(*map(float,input().split())) print("Addition: " + str(A+B)) print("Subtraction: " + str(A-B))Enter real and imaginary part of complex No - 1(separeated by space)
Enter real and imaginary part of complex No - 2(separeated by space)
Here, we have entered two complex numbers, containing their real and imaginary parts.
Now, these numbers are passed to the complex function, defined by us.
After writing (A+B) python will automatically call the __add__() function because of ( + ) symbol. The same will happen for ( - ) symbol, the __sub__() function will be called.
Our function will now add and subtract, both real and imaginary parts of the numbers together, simultaneously.
Now, the results will be passed to the __str()__ function, which will concatenate both the real and imaginary parts together.