如果我有这样的脚本:
import sys
def square(x):
return x*x
def cube(x):
return x**3
如何返回程序 ['square', 'cube']
中本地定义的所有函数的列表,而不是导入的函数。
当我尝试 dir()
时,它们被包括在内,但所有变量和其他导入的模块也是如此。我不知道将什么放入 dir
以引用本地执行文件。
最佳答案
l = []
for key, value in locals().items():
if callable(value) and value.__module__ == __name__:
l.append(key)
print l
所以一个文件的内容是:
from os.path import join
def square(x):
return x*x
def cube(x):
return x**3
l = []
for key, value in locals().items():
if callable(value) and value.__module__ == __name__:
l.append(key)
print l
打印:
['square', 'cube']
本地作用域也有效:
def square(x):
return x*x
def encapsulated():
from os.path import join
def cube(x):
return x**3
l = []
for key, value in locals().items():
if callable(value) and value.__module__ == __name__:
l.append(key)
print l
encapsulated()
仅打印出来:
['cube']
关于python - 在python中获取本地定义的函数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18451541/