From 1da4f731a5b1e110d00c4775abee0f8ac9d4b90c Mon Sep 17 00:00:00 2001 From: Donald Calloway Date: Wed, 24 Sep 2025 09:16:58 -0700 Subject: [PATCH] Demo of operator overloading in Python --- operator_overloading.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 operator_overloading.py diff --git a/operator_overloading.py b/operator_overloading.py new file mode 100644 index 0000000..4cd308f --- /dev/null +++ b/operator_overloading.py @@ -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 \ No newline at end of file