您的位置:首页 > 编程语言 > Python开发

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

2017-07-24 10:10 811 查看

如何控制对象可变性

对象可变性(mutation),可变(mutable)

# -*- coding:utf-8 -*-
the_name = ['Allen']
print the_name

other_name = the_name
other_name += ['Moore']
print other_name

print the_name


['Allen']
['Allen', 'Moore']
['Allen', 'Moore']


# -*- coding:utf-8 -*-
def append_to(item, target=[]):
target.append(item)
return target

target=append_to(12)
print target
target=append_to(23)
print target
target=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 target

target=append_to(12)
print target
target=append_to(23)
print target
target=append_to(34)
print target


[12]
[23]
[34]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐