Python3判断变量/对象是否定义的两种方法

locals和dir

  1. 使用内置函数**locals()**:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# locals():获取已定义对象字典
# testvar未定义的判断
if 'testvar' in locals().keys():
   print("testvar已定义")
else:
   print("testvar未定义")
  1. 使用内置函数**dir()**:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# dir():获取已定义对象列表
# testvar未定义的判断
if 'testvar' in dir():
   print("testvar已定义")
else:
   print("testvar未定义")

猜你喜欢

转载自blog.csdn.net/mengyangcust/article/details/84744846