python - 即使 "if var:"根本不存在,怎么说 "var"?

标签 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/

相关文章:

python - 递归获取嵌套列表的总和

python - 基于匹配的 Python 中的第一列合并数据

linux - 如何使用python代码在CentOS中重置系统代理

python - 如何让 pip 指向更新版本的 Python

python-2.7 - python中的连接组件标记

python - Tensorflow - 我是否正确恢复模型?

python - 有没有办法在一组日期范围之间定位数据框?

Python:尝试通过在名片上移动外部边框来获取用户输入

python - 备用 python 实现版本号是否暗示它们提供相同的语法?

使用 csv 或 pandas 模块的 python csv 到字典