Module-5_Classes and Objects
Module-5_Classes and Objects
Dept of MTE
• Explanation: In Python, classes provide a means of bundling
data and functionality together. Creating new classes allows you
to define custom data types.
• Notes: - Class is a blueprint; object is an instance. - Object-
Oriented Programming (OOP) supports modularity and code
reuse.
Programmer-defined Types
print("Width:", box.width)
print("Height:", box.height)
• Explanation: Illustrates object creation and attribute assignment using
Rectangle class.
• Notes: - Create Rectangle() object. - Set attributes like width, height.
Instances as Return Values
• Functions can return object instances.
• Example:
def grow(box, dwidth, dheight):
box.width += dwidth
box.height += dheight
return rect
Dept of MTE
• grow() that modifies the dimensions of a Rectangle object by
increasing its width and height
• Explanation: Functions can create and return new objects.
• Notes: - Helps modularize object creation and manipulation.
class Rectangle:
pass
# Create object and assign attributes:
box = Rectangle()
box.width = 100
box.height = 200
print("Width:", box.width)
print("Height:", box.height)
print("Width:", box.width)
print("Height:", box.height)
print("Before move:", box.corner.x, box.corner.y)
Dept of MTE
# Move the rectangle
move(box, 5, 10)
Dept of MTE
• Explanation: Create a class to represent time data
(hours, minutes, seconds).
• Notes: - Class Time holds multiple related attributes.
class Time(object):
"""represents the time of day.
attributes: hour, minute, second"""
We can create a new Time object and assign
attributes for hours, minutes, and seconds:
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
Dept of MTE
class Time:
pass
Dept of MTE
• Explanation: Functions that change the contents of an
object.
• Notes: - Opposite of pure functions. - Can lead to side-
effects.
class Time:
pass
def add_time(t1, t2):
result = Time()
# Add seconds
result.second = t1.second + t2.second
result.minute = t1.minute + t2.minute
result.hour = t1.hour + t2.hour
# Adjust for overflow
Dept of MTE
if result.second >= 60:
result.second -= 60
result.minute += 1
if result.minute >= 60:
result.minute -= 60
result.hour += 1
return result
# Create first Time object
time1 = Time()
time1.hour = 11
time1.minute = 59
time1.second = 30
# Print result
print(f"Sum of time: {sum_time.hour:02d}:{sum_time.minute:02d}:
Prototyping vs Planning
t = Time()
Dept of MTE t.hour = 9
t.minute = 5
t.second = 3
t.print_time()
Printing Objects
• Constructor method.
class Time:
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
Dept of MTE self.second = second