Briefly explain printing of objects and objects are mutable with example

Printing of Objects

  • When an object is printed using print(object), Python calls its __str__() method to get a readable string.

Example (from 17.6):

class Time:
    def __str__(self):
        return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

time = Time(9, 45)
print(time)  # Output: 09:45:00

This provides a human-readable output when printing an object.


Objects Are Mutable

  • In Python, objects like instances of classes are mutable.
  • This means their attributes can be changed after the object is created.

Example (from 15.5):

box = Rectangle()
box.width = 100.0
box.height = 200.0

box.width = box.width + 50
box.height = box.height + 100

Modified values:

box.width  → 150.0
box.height → 300.0

Functions can also modify objects:

def grow_rectangle(rect, dwidth, dheight):
    rect.width += dwidth
    rect.height += dheight

Calling:

grow_rectangle(box, 50, 100)
# Now box.width = 200.0, box.height = 400.0

This shows that when an object is passed to a function, changes to its attributes affect the original object.

Leave a Reply

Your email address will not be published. Required fields are marked *