Python函数传址调用 python函数传地址( 三 )


Python在heap中分配的对象分成2类:
不可变对象(immutable object):Number(int、float、bool、complex)、String、Tuple. 采用等效于“传引用”的方式 。
可变对象(mutable object):List、dictionary.采用等效于“传值”的方式 。
3. del 是删除引用而不是删除对象,对象由自动垃圾回收机制(GC)删除
看这个例子:
x = 1
del x x
Traceback (most recent call last):
File "pyshell#28", line 1, in module
x
NameError: name 'x' is not defined x = ['Hello','world'] y = x y
['Hello', 'world'] x
['Hello', 'world'] del x x
Traceback (most recent call last):
File "pyshell#32", line 1, in modulex
NameError: name 'x' is not defined y
['Hello', 'world']
可以看到x和y指向同一个列表,但是删除x后 , y并没有受到影响 。这是为什么呢?
The reason for this is that you only delete the name,not the list itself,In fact ,there is no way to delete values in python(and you don’t really need to because the python interpreter does it by itself whenever you don’t use the value anymore)
举个例子,一个数据(比如例子中的列表),就是一个盒子,我们把它赋给一个变量x,就是好像把一个标签x贴到了盒子上,然后又贴上了y,用它们来代表这个数据,但是用del删除这个变量x就像是把标有x的标签给撕了,剩下了y的标签 。
再看一个例子:
shoplist = ['apple', 'mango', 'carrot', 'banana']print ('The first item I will buy is', shoplist[0])
olditem = shoplist[0]del shoplist[0]#del的是引用,而不是对象print ('I bought the',olditem)print ('My shopping list is now', shoplist)print(shoplist[0])
结果为:
The first item I will buy is apple
I bought the apple
My shopping list is now ['mango', 'carrot', 'banana']
mango
实例补充:
#!/usr/bin/evn python# -*- coding:utf-8 -*-# Author: antcolonies'''python中的内置方法del不同于C语言中的free和C++中的delete
(free和delete直接回收内存,当然存储于该内存的对象也就挂了)
Python都是引用,垃圾回收为GC机制'''
'''if __name__ == '__main__':
a = 1# 对象 1 被 变量a引用,对象1的引用计数器为1
b = a# 对象1 被变量b引用 , 对象1的引用计数器加1
c = a# 对象1 被变量c引用,对象1的引用计数器加1
del a# 删除变量a,解除a对1的引用,对象1的引用计数器减1
del b# 删除变量b , 解除b对1的引用 , 对象1的引用计数器减1
print(c)# 1'''
if __name__=='__main__':
li=['one','two','three','four','five']# 列表本身不包含数据'one','two','three','four','five' , 而是包含变量:li[0] li[1] li[2] li[3] li[4]
first=li[0]# 拷贝列表,也不会有数据对象的复制,而是创建新的变量引用
del li[0]print(li)# ['two','three','four','five']
print(first)# one
list1 = lidel liprint(list1)# ['two', 'three', 'four', 'five']#print(type(li))# NameError: name 'li' is not defined
关于Python函数传址调用和python函数传地址的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

推荐阅读