Asi*_*aza 3 python python-2.7 python-3.x
在Python中,如何将函数的名称作为字符串?
我想将str.capitalize()函数的名称作为字符串.看来函数有一个__name__属性.当我做
print str.__name__
Run Code Online (Sandbox Code Playgroud)
我按预期得到了这个输出:
str
Run Code Online (Sandbox Code Playgroud)
但是当我跑步时,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
Run Code Online (Sandbox Code Playgroud)
同样的,
greeting = 'hello, world'
print greeting.capitalize().__name__
Run Code Online (Sandbox Code Playgroud)
给出了这个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__name__'
Run Code Online (Sandbox Code Playgroud)
什么地方出了错?
Asi*_*aza 11
greeting.capitalize是一个函数对象,该对象具有.__name__您可以访问的属性.但是greeting.capitalize()调用函数对象并返回greeting字符串的大写版本,并且该字符串对象没有.__name__属性.(但即使它确实有.__name__,它也是字符串的名称,而不是用于创建字符串的函数的名称).你不能这样做,str.capitalize()因为当你调用"原始" str.capitalize函数时,你需要传递一个字符串参数,它可以大写.
所以你需要这样做
print str.capitalize.__name__
Run Code Online (Sandbox Code Playgroud)
要么
print greeting.capitalize.__name__
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1863 次 |
| 最近记录: |