Possible Duplicate:
Easy way to check that variable is defined in python?
How do I check if a variable exists in Python?確定是否變量在Python
定義你怎麼知道一個變量是否已經被設置爲在運行時代碼一個特別的地方?這並不總是顯而易見的,因爲(1)變量可以被有條件地設置,並且(2)變量可以被有條件地刪除。我正在尋找Perl中的defined()
或PHP中的isset()
或Ruby中的defined?
。
if condition:
a = 42
# is "a" defined here?
if other_condition:
del a
# is "a" defined here?
Duplicates:http://stackoverflow.com/questions/843277/python-checking-variable-existing,http://stackoverflow.com/questions/750298/easy-way-to-check-that-variable-is -python -defined, – carl 2009-10-20 06:50:58
請請,請不要「有條件地」設置一個變量。這只是可怕的,可怕的設計。始終,始終提供所有邏輯路徑。請不要繼續這樣做。 – 2009-10-20 10:35:38
+1 S.Lott anwser。事實上,有辦法做到這一點並不意味着你應該在一個新的項目中使用它。 – 2010-03-31 13:48:06