Demo of operator overloading in Python
This commit is contained in:
parent
555a1c30ca
commit
1da4f731a5
14
operator_overloading.py
Normal file
14
operator_overloading.py
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
# Example of operator overloading in Python - defining a custom class with overloaded __add__ operator
|
||||||
|
|
||||||
|
class Vector:
|
||||||
|
def __init__(self, x, y):
|
||||||
|
self.x = x
|
||||||
|
self.y = y
|
||||||
|
|
||||||
|
def __add__(self, other):
|
||||||
|
return Vector(self.x + other.x, self.y + other.y)
|
||||||
|
|
||||||
|
v1 = Vector(2, 3)
|
||||||
|
v2 = Vector(4, 5)
|
||||||
|
v3 = v1 + v2 # Uses overloaded __add__ method
|
||||||
|
print(v3.x, v3.y) # 6 8
|
||||||
Loading…
Reference in New Issue
Block a user