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

问题描述

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

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:13