如何检查变量是否存在?

try:
   myVar
except NameError:
   # Do something.

答案

if 'myVar' in locals():
  # myVar exists.
if 'myVar' in globals():
  # myVar exists.
if hasattr(obj, 'attr_name'):
  # obj.attr_name exists.
try:
    myVar
except NameError:
    myVar = None

# Now you're free to use myVar without Python complaining.
if myVar is not None:
    # Do something
my_variable = None

def InitMyVariable():
  global my_variable
  if my_variable is None:
    my_variable = ...
'var' in dir(obj)
>>> class Something(object):
...     pass
...
>>> c = Something()
>>> c.a = 1
>>> 'a' in dir(c)
True
>>> 'b' in dir(c)
False
class InitMyVariable(object):
  my_variable = None

def __call__(self):
  if self.my_variable is None:
   self.my_variable = ...
def InitMyVariable():
  if InitMyVariable.my_variable is None:
    InitMyVariable.my_variable = ...
InitMyVariable.my_variable = None

catch在 Python 中except 。除此之外,对于这种简单情况也很好。有一个AttributeError可用于检查对象是否具有属性。

# Search for entry.
for x in y:
  if x == 3:
    found = x

# Work with found entry.
try:
  print('Found: {0}'.format(found))
except NameError:
  print('Not found')
else:
  # Handle rest of Found case here
  ...