【问题标题】:Get function name as a string in python [duplicate]在python中获取函数名作为字符串[重复]
【发布时间】:2011-10-31 19:22:04
【问题描述】:

可能重复:
How do I get the name of a function or method from within a Python function or method?
How to get the function name as string in Python?

我有一个名为 func 的函数,我希望能够将函数名称作为字符串获取。

伪蟒蛇:

def func () :
    pass

print name(func)

这将打印 'func'。

【问题讨论】:

  • 想知道函数的名称通常是设计欠佳的标志。为什么你想知道它被定义的名字?你将如何使用它?你知道函数是一个对象,并且可以像 Python 中的任何其他值一样对待吗?
  • 在大多数情况下,我会同意你的看法。然而,在我的特殊情况下,我正在制作一个工具,可以打印出关于任意函数的某些信息。我想在打印输出中显示函数的名称。它没有任何形式的结构位置。
  • 这并不总是坏事。例如,unittest 使用函数的名称来检测应该运行的函数。

标签: python function introspection


【解决方案1】:

这很简单。

print func.__name__

编辑:但你必须小心:

>>> def func():
...     pass
... 
>>> new_func = func
>>> print func.__name__
func
>>> print new_func.__name__
func

【讨论】:

  • 另外,一个方便的提示:使用dir 内置函数可以很容易地回答像您这样的简单问题。例如dir(func) 返回一个列表,'__name__' 作为其中一项。
  • +1 评论的答案
【解决方案2】:

使用__name__

例子:

def foobar():
    pass

bar = foobar

print foobar.__name__   # prints foobar
print bar.__name__   # still prints foobar

有关使用 python 进行自省的概述,请查看http://docs.python.org/library/inspect.html

【讨论】:

    【解决方案3】:

    还有几种方法:

    >>> def foo(arg):
    ...     return arg[::-1]
    >>> f = foo
    >>> f.__name__
    'foo'
    >>> f.func_name
    'foo'
    >>> f.func_code.co_name
    'foo'
    

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 2010-12-06
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 2023-03-13
      相关资源
      最近更新 更多