Python 方法名称末尾的括号是什么?

What are the parentheses for at the end of Python method names?

我是 Python 和一般编程的初学者。现在,我无法理解内置或用户创建的方法名称末尾空括号的功能。例如,如果我写:

print "This string will now be uppercase".upper()

...为什么在"upper?" 后面有一对空括号它有什么作用吗?有没有放东西进去的情况?谢谢!

因为没有那些你只是引用了方法对象。 他们你告诉Python你想调用这个方法。

在Python中,函数和方法是一阶对象。您可以存储该方法以供以后使用而无需调用它,例如:

>>> "This string will now be uppercase".upper
<built-in method upper of str object at 0x1046c4270>
>>> get_uppercase = "This string will now be uppercase".upper
>>> get_uppercase()
'THIS STRING WILL NOW BE UPPERCASE'

此处 get_uppercase 存储对字符串的绑定 str.upper 方法的引用。只有当我们在引用之后添加 () 才是真正调用的方法。

这里的方法没有参数没有区别。您仍然需要告诉 Python 进行实际调用。

(...) 部分称为 Call expression,在 Python 文档中明确列为单独的表达式类型:

A call calls a callable object (e.g., a function) with a possibly empty series of arguments.

括号表示你要调用方法

upper() returns 应用于字符串的方法的值

如果你简单地说upper,那么它returns一个方法,而不是应用该方法时得到的值

>>> print "This string will now be uppercase".upper
<built-in method upper of str object at 0x7ff41585fe40>
>>> 

upper() 是一个 command 要求上层方法 运行,而 upper 是一个 reference 到方法本身。例如,

upper2 = 'Michael'.upper
upper2() # does the same thing as 'Michael'.upper() !