判斷變量是否定義
參考:
python中檢測某個變量是否有定義
dir介紹
你是否會碰到如下情形:
# 如果C有值就取C,否則自定義為8
a = 8 if not c else c
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
a = 8 if not c else c
NameError: name 'c' is not defined
呵呵漾橙,結果,發(fā)現(xiàn)c未定義楞卡,not defined霜运,不是None
碰到這種問題該怎么解決呢脾歇?
目前判斷變量有二種方式:
- 一般方式:try···except
try:
a = 8 if not c else c
except:
a = 8
- dir() /local()判斷
我們先來看看IDLE 上他們的表現(xiàn)
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "copyright", "credits" or "license()" for more information.
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> locals()
{'__doc__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__spec__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
>>> locals().key()
dict_keys(['__doc__', '__package__', '__builtins__', '__spec__', '__name__', '__loader__'])
我需要判斷變量是否在name中
# local() 方式就不介紹了,本質一樣
a = 8 if not 'c' in dir() or not c else 8
# 查看一下dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a']
dir()介紹
中文說明:不帶參數(shù)時淘捡,返回當前范圍內的變量藕各、方法和定義的類型列表;帶參數(shù)時焦除,返回參數(shù)的屬性激况、方法列表。如果參數(shù)包含方法dir()膘魄,該方法將被調用乌逐。如果參數(shù)不包含dir(),該方法將最大限度地收集參數(shù)信息创葡。
參數(shù)object: 對象浙踢、變量、類型灿渴。
版本:該函數(shù)在python各個版本中都有洛波,但是每個版本中顯示的屬性細節(jié)有所不同。使用時注意區(qū)別骚露。
代碼示例:
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> import struct
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'struct']
>>> dir(struct)
['Struct', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from']
>>> class Person(object):
... def __dir__(self):
... return ["name", "age", "country"]
...
>>> dir(Person)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__','__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> tom = Person()
>>> dir(tom)
['age', 'country', 'name']