确定Python中函数是在哪个文件中定义的

问题描述 投票:0回答:5

我正在以编程方式打印出 python 中的函数列表。 我可以从name

获取名字
for ifunc,func in enumerate(list_of_functions):
    print(str(ifunc)+func.__name__)

如何获取定义函数的源文件名?

如果函数是对象的属性,如何获取父对象的类型?


可移植性 python2/3 是必须的

python function introspection
5个回答
23
投票
func.__module__

将返回定义它的模块

func.__globals__['__file__']

将返回定义该文件的整个路径。仅适用于用户定义的函数


7
投票

如何获取定义函数的源文件名...?

import inspect
inspect.getfile(func)

如果函数是对象的属性,如何获取父对象的类型?

获取方法的类(即当该函数是对象的属性时):

if inspect.ismethod(func):
    the_class = func.__self__.__class__

参考:https://docs.python.org/3/library/inspect.html


1
投票

要获取文件名,只需使用 -

print(os.path.basename(__file__))

如果你想要完整的文件路径,你可以使用

print __file__

1
投票

如此处所述 https://docs.python.org/3/library/inspect.html

func.__globals__
返回定义函数的全局命名空间。


0
投票

您可以使用

__file__
变量。

print(__file__)

© www.soinside.com 2019 - 2024. All rights reserved.