如何动态获取函数名称

时间:2015-07-15 07:19:38

标签: python

我可以将those about to be executed functions放入functions_results。

我打印出结果,但我无法获得函数本身的名称。

例如,

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())

名称在我的情况下不起作用

  

打印(ⅰ。的名称

    (type(self).__name__, name))
AttributeError: 'DataFrame' object has no attribute '__name__'

3 个答案:

答案 0 :(得分:1)

您可以通过function.__name__访问此内容。

答案 1 :(得分:1)

您可以使用__name__属性来获取您的函数名称:

示例:

>>> def my_func():
...   print 'my_func'
... 
>>> my_func.__name__
'my_func'

阅读有关python模块https://docs.python.org/2/tutorial/modules.html#modules

的更多信息

另请注意,因为您已在functions_results内调用了您的功能:

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__'
>>> 

因此,为了解决这个问题,您需要在不在列表中调用它的情况下放置该函数:

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

另请注意,您无法再次进行第二次函数调用:

schedules("2014-06-01", "2015-03-01")

并且为了解决这个问题,您可以使用hasattr(obj, '__call__')方法(以及python3中的callable)检查i是否为函数类型,然后获取其名称:

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

答案 2 :(得分:0)

通过function.__name__.

访问此内容
>>> def a():
...     pass
... 
>>> a.__name__
'a'
>>> 
相关问题