这里有四个简单的assert调用:
>>> assert 1==2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
>>> assert 1==2, "hi"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: hi
>>> assert(1==2)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
>>> assert(1==2, "hi")
Run Code Online (Sandbox Code Playgroud)
请注意,最后一个不会引发错误.调用带或不带括号的断言会导致这种行为有什么区别?我的做法是使用括号,但上面的建议我不应该这样做.
我在Python中创建了一个列表
>>> my_list = [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
现在,如果我想删除列表,我想使用del运算符
>>> del my_list
Run Code Online (Sandbox Code Playgroud)
这很好用,可能是使用它的一般方法.但在某个地方,我偶然发现了一种不寻常的语法
>>> del[my_list]
Run Code Online (Sandbox Code Playgroud)
而这也是一样的!而现在我有点困惑del del实际工作.我可以del通过内置语句理解以前的语法,但第二种语法看起来像是对我的索引.
为什么这段代码按照它的方式工作?
x = 3
print(dir()) #output indicates that x is defined in the global scope
del (x)
print(dir()) #output indicates that x is not defined in the global scope
Run Code Online (Sandbox Code Playgroud)
我的理解是它del是Python中的关键字,接下来del应该是一个名称.(name)不是名字.为什么这个例子似乎表明它的del (name)作用相同del name?