Operator overloading
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.
위 내용을 요약하면 클래스 인스턴스에 적용할 때 연산자 기호(Operator) 의 의미를 지정하는 함수를 선언하는 것을 말합니다. 즉, 기본 제공하는 연산기호를 클래스 단위로 다시 정의할 수 있는 것을 말합니다. 아래의 코드 예시를 보고 설명해보겠습니다.
Python Code
Basic operator usage
기본적으로 Python에서는 문자열, 숫자에 대한 덧셈, 뺄셈 등 기본 연산자를 사용할 수 있습니다.
# Python program to show use of
# + operator for different purposes.
print(1 + 2)
# concatenate two strings
print("Geeks"+"For")
# Product two numbers
print(3 * 4)
# Repeat the String
print("Geeks"*4)
'''
[ Output ]
3
GeeksFor
12
GeeksGeeksGeeksGeeks
'''
Python
복사
__add__() method
클래스 끼리 덧셈 뺄셈을 할 때 다음과 같이 __add__() method를 이용하여 클래스끼리의 덧셈이 가능하는 것을 볼 수 있습니다.
# Python Program illustrate how
# to overload an binary + operator
# And how it actually works
class A:
def __init__(self, a):
self.a = a
# adding two objects
def __add__(self, o):
return self.a + o.a
ob1 = A(1)
ob2 = A(2)
ob3 = A("Geeks")
ob4 = A("For")
print(ob1 + ob2)
print(ob3 + ob4)
# Actual working when Binary Operator is used.
print(A.__add__(ob1, ob2))
print(A.__add__(ob3, ob4))
#And can also be Understand as :
print(ob1.__add__(ob2))
print(ob3.__add__(ob4))
'''
[ Output ]
3
GeeksFor
3
GeeksFor
3
GeeksFor
'''
Python
복사
Add operator
하지만 Python에서 Operator overloading을 활용하여 덧셈 연산자를 이용하면 다음과 같이 결과를 볼 수 있습니다.
# Python Program to perform addition
# of two complex numbers using binary
# + operator overloading.
class complex:
def __init__(self, a, b):
self.a = a
self.b = b
# adding two objects
def __add__(self, other):
return self.a + other.a, self.b + other.b
Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2
print(Ob3)
'''
[ Output ]
(3, 5)
'''
Python
복사
Comparison operators
# Python program to overload
# a comparison operators
class A:
def __init__(self, a):
self.a = a
def __gt__(self, other):
if(self.a>other.a):
return True
else:
return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
print("ob1 is greater than ob2")
else:
print("ob2 is greater than ob1")
'''
[ Output ]
ob2 is greater than ob1
'''
Python
복사
Operators
Binary Operators
Operator | Magic Method |
+ | __add__(self, other) |
– | __sub__(self, other) |
* | __mul__(self, other) |
/ | __truediv__(self, other) |
// | __floordiv__(self, other) |
% | __mod__(self, other) |
** | __pow__(self, other) |
>> | __rshift__(self, other) |
<< | __lshift__(self, other) |
& | __and__(self, other) |
| | __or__(self, other) |
^ | __xor__(self, other) |
Comparison Operators
Operator | Magic Method |
< | __lt__(self, other) |
> | __gt__(self, other) |
<= | __le__(self, other) |
>= | __ge__(self, other) |
== | __eq__(self, other) |
!= | __ne__(self, other) |
Assignment Operators
Operator | Magic Method |
-= | __isub__(self, other) |
+= | __iadd__(self, other) |
*= | __imul__(self, other) |
/= | __idiv__(self, other) |
//= | __ifloordiv__(self, other) |
%= | __imod__(self, other) |
**= | __ipow__(self, other) |
>>= | __irshift__(self, other) |
<<= | __ilshift__(self, other) |
&= | __iand__(self, other) |
|= | __ior__(self, other) |
^= | __ixor__(self, other) |
Unary Operators
Operator | Magic Method |
– | __neg__(self) |
+ | __pos__(self) |
~ | __invert__(self) |