如何检查变量是否存在?我想检查变量是否存在。现在我在做这样的事情:try:
myVarexcept NameError:
# Do something.没有例外的其他方式吗?
3 回答

子衿沉夜
TA贡献1828条经验 获得超3个赞
if 'myVar' in locals(): # myVar exists.
if 'myVar' in globals(): # myVar exists.
if hasattr(obj, 'attr_name'): # obj.attr_name exists.

宝慕林4294392
TA贡献2021条经验 获得超8个赞
try: myVarexcept NameError: myVar = None# Now you're free to use myVar without Python complaining.
添加回答
举报
0/150
提交
取消