在python中获取本地定义函数的列表 [英] Getting a list of locally-defined functions in python

查看:43
本文介绍了在python中获取本地定义函数的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的脚本:

import sys

def square(x):
    return x*x

def cube(x):
    return x**3

如何返回程序['square', 'cube']中本地定义的所有功能的列表,而不是导入的功能.

How can I return a list of all the functions defined locally in the program ['square', 'cube'], and not the ones imported.

当我尝试dir()时,它们包括在内,但是所有变量和其他导入的模块也包括在内.我不知道要放入dir来引用本地执行文件的内容.

They are included when I try dir() but so are all the variables and other imported modules. I don't know what to put into dir to refer to the locally executing file.

推荐答案

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中获取本地定义函数的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆