首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。