gpt4 book ai didi

python - 为什么变量名两边带括号的 del(x) 有效?

转载 作者:行者123 更新时间:2023-12-02 22:19:04 24 4
gpt4 key购买 nike

为什么这段代码会这样工作?

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

我的理解是,del是Python中的关键字,del后面的应该是一个名字。 (name) 不是名称。为什么该示例似乎表明 del (name)del name 的作用相同?

最佳答案

del statement 的定义是:

del_stmt ::=  "del" target_list

并根据 target_list 的定义:

target_list ::=  target ("," target)* [","]
target ::= identifier
| "(" target_list ")"
| "[" [target_list] "]"
| ...

您可以看到允许在目标列表两边使用括号。

例如,如果您定义x,y = 1,2,则所有这些都是允许的并且具有相同的效果:

del x,y
del (x,y)
del (x),[y]
del [x,(y)]
del ([x], (y))

关于python - 为什么变量名两边带括号的 del(x) 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39028249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com