模块也是一等对象
当前模块内省
globals():
返回一个字典,表示当前的全局符号表。这个符号表始终针对当前模块(对函数或方法来说,是指定义它们的模块,
而不是调用他它们的模块)
# test_02.py
gol_num = 3
def a():
print('a')
def b():
print('b')
def c():
print('c')
if __name__ == '__main__':
resu = [k_v for k_v in globals().items()]
print(resu)
# for name in globals().items():
# print(name) error: RuntimeError: dictionary changed size during iteration
输出:
[('__name__', '__main__'), ('__doc__', None), ('__package__', None), ('__loader__', <_frozen_importlib_external.SourceFileLoader object at 0x0000026A265F4880>), ('__spec__', None), ('__annotations__', {}), ('__builtins__', <module 'builtins' (built-in)>), ('__file__', 'E:\\PyProject\\homework\\20220201\\test_02.py'), ('__cached__', None), ('gol_num', 3), ('a', <function a at 0x0000026A26533E20>), ('b', <function b at 0x0000026A2696ED40>), ('c', <function c at 0x0000026A2696EDD0>)]
其他模块
# test_01.py
import inspect
# 被检查的模块
import test_02
if __name__ == '__main__':
# inspect.getmembers(module_name, inspect.isfunction): 注意:第一个参数是模块名称, 第二个参数没有()
# name: 函数名字, func: test_02中的函数对象
for name, func in inspect.getmembers(test_02, inspect.isfunction):
print(f"name:{name}, func:{func}")
# 调用test_02.py 中的函数
func()
out:
name:a, func:<function a at 0x00000220177DF640>
a func ran
name:b, func:<function b at 0x00000220178870A0>
b func ran
name:c, func:<function c at 0x0000022017887130>
c func ran