python - 如何获取函数的名称作为字符串?

标签 python python-2.7 python-3.x

在 Python 中,如何获取字符串形式的函数名称?

我想获取字符串形式的 str.capitalize() 函数的名称。该函数似乎具有 __name__ 属性。当我做的时候

print str.__name__

如预期的那样,我得到了这个输出:

str

但是当我运行 str.capitalize().__name__ 时,我得到了一个错误,而不是得到名称“capitalize”。

> Traceback (most recent call last):
> File "string_func.py", line 02, in <module>  
>    print str.capitalize().__name__
> TypeError: descriptor 'capitalize' of 'str' object needs an argument

同样,

greeting = 'hello, world'
print greeting.capitalize().__name__

给出这个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__name__'

出了什么问题?

最佳答案

greeting.capitalize 是一个函数对象,该对象具有您可以访问的 .__name__ 属性。但是 greeting.capitalize() 调用函数对象并返回 greeting 字符串的大写版本,而该字符串对象没有 .__name__属性。 (但即使它确实有一个 .__name__,它也是字符串的名称,而不是用于创建字符串的函数的名称)。而且您不能执行 str.capitalize(),因为当您调用“原始”str.capitalize 函数时,您需要向它传递一个它可以大写的字符串参数。

所以你需要做

print str.capitalize.__name__

print greeting.capitalize.__name__

关于python - 如何获取函数的名称作为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44226573/

相关文章:

python - 从 csv 文件中提取日期范围并将其写入新文件,没有任何反应

Python SMTP 错误代码处理

python - 如何避免Python中的if语句多次重复条件?

python - 如何访问 pandas DataFrame 中除第一列之外的所有列?

python - 使用充当 UDP 回显的程序确定服务器可用性

python - 子进程超时 : What to do after TimeoutExpired Exception?

Python 安装程序 : "Error writing to file C:\Python27\pythonw.exe"

python - 为什么 next() 总是显示相同的值?

python - 使用 sql python/tkinter 填充下拉列表

python - 将参数传递给线程python