0% found this document useful (0 votes)
11 views5 pages

Lab6 Handout

This document is a lab handout for a course on Object Oriented Programming at Liaquat University, focusing on operator overloading in Python. It explains the concept of operator overloading, provides examples of how to implement it for custom classes, and outlines the task of writing a Python program to overload division, power, and floor division operators. The document includes code snippets demonstrating the overloading of various operators such as addition and subtraction for user-defined data types.

Uploaded by

thewriterdeenan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views5 pages

Lab6 Handout

This document is a lab handout for a course on Object Oriented Programming at Liaquat University, focusing on operator overloading in Python. It explains the concept of operator overloading, provides examples of how to implement it for custom classes, and outlines the task of writing a Python program to overload division, power, and floor division operators. The document includes code snippets demonstrating the overloading of various operators such as addition and subtraction for user-defined data types.

Uploaded by

thewriterdeenan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Institute of Biomedical Engineering and Technology

Liaquat University of Medical and Health Sciences Jamshoro, Sindh.

Subject: Object Oriented Programming Batch: 2024 Year: 1st, Semester: 2nd
Lab Handout-06

Name: ________________________________ Roll No: ________________________

Date: _________________ Signature of Tutor: __________________

Implementation of operator overloading

Objectives:

Experimenting operator overloading features.

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.

Operator overloading is a powerful feature in object-oriented programming (OOP) that


allows developers to redefine the behavior of operators for their custom data types,
enabling more expressive, readable, and maintainable code and when working with user-
defined data types, such as classes or structures. This means that operators like +, -, *, /,
==, !=, etc. can be redefined to perform specific operations on objects of a particular
class. In other words, operator overloading enables developers to create custom operators
for their classes, allowing them to perform operations that are specific to their data type.

TYPES OF OPERATORS OVERLOADING:


1. OVERLOADING ARITHMETIC OPERATORS:
2. OVERLOADING COMPARISON OPERATORS:

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 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 __add__(self, other):


# Check if both operands are instances of CustomAddition
if isinstance(other, CustomAddition):
# Adding two instances of CustomAddition
result_value = self.value + other.value
return CustomAddition(result_value)
elif isinstance(other, (int, float)):
# Adding a number to CustomAddition
result_value = self.value + other
return CustomAddition(result_value)
elif isinstance(other, str):
# Concatenating a string to CustomAddition
result_value = str(self.value) + other
return CustomAddition(result_value)
else:
# Unsupported operand types
raise TypeError(f"Unsupported operand type: {type(other)}")

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}")

str1 = CustomAddition("Hello, ")


str2 = CustomAddition("world!")
result_strings = str1 + str2
print(f"Concatenated strings: {result_strings}")

Example

class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag

def __add__(self, other):


if isinstance(other, ComplexNumber):
# Adding two complex numbers
result_real = self.real + other.real
result_imag = self.imag + other.imag
return ComplexNumber(result_real, result_imag)
else:
# Unsupported operand type
raise TypeError(f"Unsupported operand type: {type(other)}")

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 __sub__(self, other):


if isinstance(other, ComplexNumber):
# Subtracting two complex numbers
result_real = self.real - other.real
result_imag = self.imag - other.imag
return ComplexNumber(result_real, result_imag)
else:
# Unsupported operand type
raise TypeError(f"Unsupported operand type: {type(other)}")

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 __mul__(self, scalar):


if isinstance(scalar, (int, float)):
# Multiplying a vector by a scalar
result_x = self.x * scalar
result_y = self.y * scalar
result_z = self.z * scalar
return Vector(result_x, result_y, result_z)
else:
# Unsupported operand type
raise TypeError(f"Unsupported operand type: {type(scalar)}")

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.

You might also like