本文介绍了确定变量是否在 Python 中定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何知道在运行时是否在代码中的特定位置设置了变量?这并不总是显而易见的,因为 (1) 可以有条件地设置变量,以及 (2) 可以有条件地删除变量.我正在寻找类似 Perl 中的 defined() 或 PHP 中的 isset() 或 Ruby 中的 defined? 之类的东西.

How do you know whether a variable has been set at a particular place in the code at runtime? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. I'm looking for something like defined() in Perl or isset() in PHP or defined? in Ruby.

if condition:
    a = 42

# is "a" defined here?

if other_condition:
    del a

# is "a" defined here?

推荐答案

try:
    thevariable
except NameError:
    print("well, it WASN'T defined after all!")
else:
    print("sure, it was defined.")

这篇关于确定变量是否在 Python 中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 09:14