You are here

Objects are mutable

8 September, 2015 - 10:43

You can change the state of an object by making an assignment to one of its attributes. For example, to change the size of a rectangle without changing its position, you can modify the values of width and height:

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

You can also write functions that modify objects. For example, grow_rectangle takes a Rectangle object and two numbers, dwidth and dheight, and adds the numbers to the width and height of the rectangle:

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

Here is an example that demonstrates the effect:

>>> print box.width100.0>>> print box.height200.0>>> grow_rectangle(box, 50, 100)>>> print box.width150.0>>> print box.height300.0

Inside the function, rect is an alias for box, so if the function modifies rect, box changes.

Exercise 15.2.Write a function named move_rectangle that takes a Rectangle and two numbers named dx and dy. It should change the location of the rectangle by adding dxto the x coordinate of cornerand adding dy to the y coordinate of corner.