【脚本语言系列】关于Python基础知识对象变动,你知道的事

来源:互联网 发布:c语言获取随机数 编辑:程序博客网 时间:2024/06/09 20:37

如何控制对象可变性

  • 对象可变性(mutation),可变(mutable)
# -*- coding:utf-8 -*-the_name = ['Allen']print the_nameother_name = the_nameother_name += ['Moore']print other_nameprint the_name
['Allen']['Allen', 'Moore']['Allen', 'Moore']
# -*- coding:utf-8 -*-def append_to(item, target=[]):    target.append(item)    return targettarget=append_to(12)print targettarget=append_to(23)print targettarget=append_to(34)print target
[12][12, 23][12, 23, 34]
  • 不可变(immutable)
# -*- coding:utf-8 -*-def append_to(item, target=None):    if target is None:        target = []    target.append(item)    return targettarget=append_to(12)print targettarget=append_to(23)print targettarget=append_to(34)print target
[12][23][34]
阅读全文
0 0
原创粉丝点击