python学习:参考
来源:互联网 发布:吉林省网络教育jlsedu 编辑:程序博客网 时间:2024/06/01 07:19
当你创建一个对象并给它赋一个变量的时候,这个变量仅仅 参考 那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。
一般说来,你不需要担心这个,只是在参考上有些细微的效果需要你注意。这会通过下面这个例子加以说明。
对象与参考
例9.6 对象与参考
#!/usr/bin/python
# Filename: reference.pyprint
'Simple Assignment'
shoplist = [
'apple'
,
'mango'
,
'carrot'
,
'banana'
]
mylist = shoplist
# mylist is just another name pointing to the same object!
del
shoplist[
0
]
print
'shoplist is'
, shoplist
print
'mylist is'
, mylist
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same objectprint
'Copy by making a full slice'
mylist = shoplist[:]
# make a copy by doing a full slice
del
mylist[
0
]
# remove first item
print
'shoplist is'
, shoplist
print
'mylist is'
, mylist
# notice that now the two lists are different
(源文件:code/reference.py)
输出
$ python reference.py
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']
它如何工作
大多数解释已经在程序的注释中了。你需要记住的只是如果你想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单 对象 ),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都 参考 同一个对象,那么如果你不小心的话,可能会引来各种麻烦。
给Perl程序员的注释
记住列表的赋值语句不创建拷贝。你得使用切片操作符来建立序列的拷贝。
- python学习:参考
- Python学习11:参考的使用
- 学习Python参考博文链接
- python学习参考及环境配置
- 简明python教程学习笔记之九-对象参考
- 2014/11/2 Python正则表达式学习参考
- 2014/11/9 Python模块安装学习参考
- apriori算法的代码,python实现,参考《机器学习实战》
- python学习笔记(一)基础语法 — 参考创客智造
- 学习参考
- 学习参考
- 参考学习
- python多线程参考博客
- python + gtk 参考网站
- python排序方法参考
- Python命名规范参考
- Python: 对象与参考
- Python的参考
- 数组的简单总结
- 洛谷 p1197 [JSOI2008]星球大战(并查集)
- 算法分析与设计课程作业第五周#1
- jQuery插件开发细节
- 写给现在的自己
- python学习:参考
- leetcode 639. Decode Ways II
- 实现杨辉三角
- java NIO详解(3)--FileChannel
- Linux mail命令发送邮件
- 反射的理解和使用
- ios-SDWebImage清除缓存机制
- 全屏滚动的原理及实现
- POJ