Lab6 Handout
Lab6 Handout
Subject: Object Oriented Programming Batch: 2024 Year: 1st, Semester: 2nd
Lab Handout-06
Objectives:
Introduction:
Python operators work for built-in classes. But the same operator behaves differently with
different types. For example, the + operator will perform arithmetic addition on two
numbers, merge two lists, or concatenate two strings. This feature in Python that allows
the same operator to have different meaning according to the context is called operator
overloading.
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 the compiler doesn'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 operator. For example, when we use + operator, the magic method
__add__ is automatically invoked in which the operation for + operator is defined.
Example
class CustomAddition:
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
# Example usage
num1 = CustomAddition(5)
num2 = CustomAddition(10)
result_numbers = num1 + num2
print(f"Sum of numbers: {result_numbers}")
Example
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __str__(self):
return f"{self.real} + {self.imag}j"
# Example usage
num1 = ComplexNumber(2, 3)
num2 = ComplexNumber(1, 4)
result_complex = num1 + num2
print(f"Sum of complex numbers: {result_complex}")
Example:
class Coord:
def __init__(self, y=0, z=0):
self.y = y
self.z = z
def __str__(self):
return "({0},{1})".format(self.y,self.z)
def __add__(self,other):
y = self.y + other.y
z = self.z + other.z
return Coord(y,z)
c1 = Coord(1,2)
c2 = Coord(2,3)
print(c1+c2)
Example:
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __str__(self):
return f"{self.real} - {self.imag}j"
# Example usage
num1 = ComplexNumber(5, 2)
num2 = ComplexNumber(1, 4)
result_complex = num1 - num2
print(f"Difference of complex numbers: {result_complex}")
Example:
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return f"({self.x}, {self.y}, {self.z})"
# Example usage
vector = Vector(1, 2, 3)
scalar = 2
result_vector = vector * scalar
print(f"Result of vector multiplication: {result_vector}")
Task:
Write a python program with overloading of division, power and floor division
operators.