Python 如何动态获取函数的名称

Python 如何动态获取函数的名称,python,Python,我可以将那些即将执行的函数放入函数结果中 我可以打印出结果,但无法获取函数本身的名称 比如说, functions_results = [ schedules(), schedules("2014-06-01", "2015-03-01"), ] list_of_functions_heads = [x for x in functions_results] for i in list_of_functions_heads: # this is what I want

我可以将那些即将执行的函数放入函数结果中

我可以打印出结果,但无法获取函数本身的名称

比如说,

functions_results = [
    schedules(),
    schedules("2014-06-01", "2015-03-01"),
]

list_of_functions_heads = [x for x in functions_results]
for i in list_of_functions_heads:
    # this is what I want to get
    # print(i.FUNCTION_NAME) # 'schedules()'

    print(i.head())
name在我的情况下不起作用 打印(i.名称


您可以通过
函数访问此函数。可以使用
属性获取函数名:

例如:

>>> def my_func():
...   print 'my_func'
... 
>>> my_func.__name__
'my_func'
阅读更多关于python模块的信息

还要注意,由于您在
函数\u结果中调用了函数,因此:

functions_results = [
    schedules(),
              ^ #here you called the function 
    schedules("2014-06-01", "2015-03-01"),
]
因此,您无法在循环中获取其名称。例如,如果在前面的示例中,我们希望在调用后获得函数名,python将引发一个
AttributeError

>>> my_func().__name__
my_func
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute '__name__'
>>> 
另请注意,对于第二次函数调用,不能再次执行此操作:

schedules("2014-06-01", "2015-03-01")
为了解决这个问题,您也可以使用
hasattr(obj,'.\u call\uu')
方法(以及python3中的
callable
)检查
i
是否是函数类型,然后获取其名称:

for i in list_of_functions_heads:
      if hasattr(i, '__call__'):
           print i.__name__

通过
功能访问此项。\uuuu name\uuuuu。

>>> def a():
...     pass
... 
>>> a.__name__
'a'
>>> 

您已经调用了
调度
函数,因此无法获取函数对象的名称。。什么是
schedules()
返回的
.head()
方法?名称在我的情况下不起作用,请查看我的更新thanks@user3675188你已经完全阅读了我的答案吗?我解释说你不应该调用函数并在循环中使用
hasattr
。是的,我试过了,但是
时间表(“2014-06-01”,“2015-03-01”)
我如何避免在我的方法中调用它,thanks@user3675188正如我所说,为了避免使用
hasattr
名称在我的情况下不起作用,请查看我的更新感谢这是因为
I
不是代码中的函数
i
schedules()
schedules(“2014-06-01”、“2015-03-01”)
,根据您的错误消息,它们似乎是
DataFrame
对象。如果要使用
\uuu name\uuu
,则需要确保对象实际上是一个函数。
for i in list_of_functions_heads:
      if hasattr(i, '__call__'):
           print i.__name__
>>> def a():
...     pass
... 
>>> a.__name__
'a'
>>>