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 + 50
box.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

posted @ 2014-09-29 23:17  平静缓和用胸音说爱  阅读(172)  评论(0编辑  收藏  举报