如何检查变量是否存在? [英] How do I check if a variable exists?

查看:97
本文介绍了如何检查变量是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查变量是否存在。现在,我正在执行以下操作:

I want to check if a variable exists. Now I'm doing something like this:

try:
   myVar
except NameError:
   # Do something.

还有没有其他例外的方法吗?

Are there other ways without exceptions?

推荐答案

要检查是否存在局部变量:

To check the existence of a local variable:

if 'myVar' in locals():
  # myVar exists.

要检查是否存在全局变量:

To check the existence of a global variable:

if 'myVar' in globals():
  # myVar exists.

检查对象是否具有属性:

To check if an object has an attribute:

if hasattr(obj, 'attr_name'):
  # obj.attr_name exists.

这篇关于如何检查变量是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆