Let’s take a quick lool at two statements:pass and del
<wbr></wbr>
1 pass: 空语句什么也不执行,用处颇广。
<wbr></wbr>
if name =='Ralph Auldus Melish':
print 'Welcome'
elif name == 'Enid':
#not finish yet ...
pass
elif name == 'Bill Gates':
print 'Access Denied'
<wbr></wbr>
此时,因为某些原因,我们还不知道第一个elif要做什么,所以就先用pass代替,这样调试程序可以跳过这个elif 继续执行下面的。
<wbr></wbr>
2 del<wbr> 删除</wbr>
<wbr></wbr>
看这个例子:
<wbr></wbr>
>>> x = 1
>>> del x
>>> x
<wbr></wbr>
Traceback (most recent call last):
File "<pyshell#6>", 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
<wbr></wbr>
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
x
NameError: name 'x' is not defined
>>> y
['Hello', 'world']
>>>
<wbr></wbr>
可以看到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)
<wbr></wbr>
举个例子,一个数据(比如例子中的列表),就是一个盒子,我们把它赋给一个变量x,就是好像把一个标签x贴到了盒子上,然后又贴上了y,用它们来代表这个数据,但是用del删除这个变量x就像是把标有x的标签给撕了,剩下了y的标签。
<wbr></wbr>
这就是Python的变量引用思想。
本文详细介绍了Python中pass和del两个关键字的使用方法及其应用场景。pass作为占位符,用于构造完整的语法结构但暂时不需要执行任何操作;del则用于删除变量名,释放其指向的对象引用。
1万+

被折叠的 条评论
为什么被折叠?



