<分区>
这会很好地工作:
a = 1
if a:
b = a
但这行不通:
if a:
b = a
考虑到我们明确说明,“if”语句不会被执行。
"if a exists"
那么为什么会出错呢?如果它不存在,那么就不要在该 if 语句的参数范围内做任何事情。
更新
原来“if a”的意思是……“如果 a 的值”在 python 中的意思。
我正在寻找“如果 a 存在则继续前进”的等效项
标签 python python-2.7
<分区>
这会很好地工作:
a = 1
if a:
b = a
但这行不通:
if a:
b = a
考虑到我们明确说明,“if”语句不会被执行。
"if a exists"
那么为什么会出错呢?如果它不存在,那么就不要在该 if 语句的参数范围内做任何事情。
更新
原来“if a”的意思是……“如果 a 的值”在 python 中的意思。
我正在寻找“如果 a 存在则继续前进”的等效项
最佳答案
您可以使用 locals()
:
if 'a' in locals():
# variable 'a' is defined
你也可以利用Python的请求宽恕比许可更容易的原则:
try:
b
# if we get here, variable 'b' is defined
except NameError:
# variable 'b' is not defined
如 the documentation 中所述:
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements.
关于python - 即使 "if var:"根本不存在,怎么说 "var"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25643048/