首页 > 代码库 > Objects are mutable

Objects are mutable

We 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.height + 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 += dwidth    rect.height += dheight

Here is an example that demonstrates the effect:

                       

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

 

from Thinking in Python

Objects are mutable