1 ## Python Determines if a variable has been defined2 3 detect if a variable is defined in Python4 5 The first method uses the built-in function locals ():6 locals (): Get Dictionary of defined objects7 8 'TestVar' inchlocals (). Keys ()9 Ten The second method uses the built-in function dir (): One dir (): Get a list of defined objects A - 'TestVar' inchdir () - the The third method uses the built-in function VARs (): - VARs (): Get Dictionary of defined objects - -VARs (). Has_key ('TestVar') + - +Examples of----------------applications--------------------------------- A at #TestVar Not defined - Print 'TestVar' inchlocals (). Keys () - #Output: False - - Print 'TestVar' inchdir () - #Output: False in - PrintVARs (). Has_key ('TestVar') to #Output: False + - #define TestVar theTestvar=1 * $ Print 'TestVar' inchlocals (). Keys ()Panax Notoginseng #Output: True - the Print 'TestVar' inchdir () + #Output: True A the PrintVARs (). Has_key ('TestVar') + #Output: True - $------------------------------------- $ ##说明: - if the defined function has arguments, but no arguments are called, other errors are reported, not the wrong variables undefined!!! - deffunc1 (srcdir): the PrintSrcdir - Wuyi Try: the func1 () - except: Wu Print "1111"
1 Python Determines whether a variable is defined