2017-05-28 73 views
2

在Python中,如何获得函数的名称作为字符串?如何获取函数的名称作为字符串?

我想将str.capitalize()函数的名称作为字符串。看起来该函数具有__name__属性。当我做

print str.__name__ 

我得到这个输出,符合市场预期:

str 

但是当我运行str.capitalize().__name__我得到一个错误,而不是让名称为“利用”的。

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

出了什么问题?

+0

这有什么错'str.capitalize .__ name__'或'greeting.capitalize。 __name__'? –

+0

返回错误 –

+0

如果你想要变量的名字,你必须单独发现它https://stackoverflow.com/questions/2553354/how-to-get-a-variable-name-as-a-string python –

回答

11

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

所以,你需要做的

print str.capitalize.__name__ 

print greeting.capitalize.__name__ 
4

让我们从错误中

Traceback (most recent call last):
File "", line 1, in
AttributeError: 'str' object has no attribute 'name'

具体启动

AttributeError: 'str' object has no attribute 'name'

您正在尝试

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

这将充分hello world并返回一个字符串。

由于错误状态,string没有attribute _name_

capitalize()将立即执行的功能和使用的结果,而capitalize将代表功能。

如果你想看到在JavaScript一种变通方法,

检查下面的代码片段

function abc(){ 
 
    return "hello world"; 
 
} 
 

 
console.log(typeof abc); //function 
 
console.log(typeof abc());

所以,不执行。

只需使用

greeting = 'hello, world' 
print greeting.capitalize.__name__ 
1

你不需要调用这个函数,只需使用

>>> str.capitalize.__name__