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

时光总嘲笑我的痴心妄想 提交于 2019-12-04 09:09:37

the parentheses indicate that you want to call the method

upper() returns the value of the method applied to the string

if you simply say upper, then it returns a method, not the value you get when the method is applied

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

Because without those you are only referencing the method object. With them you tell Python you wanted to call the method.

In Python, functions and methods are first-order objects. You can store the method for later use without calling it, for example:

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

Here get_uppercase stores a reference to the bound str.upper method of your string. Only when we then add () after the reference is the method actually called.

That the method takes no arguments here makes no difference. You still need to tell Python to do the actual call.

The (...) part then, is called a Call expression, listed explicitly as a separate type of expression in the Python documentation:

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

upper() is a command asking the upper method to run, while upper is a reference to the method itself. For example,

upper2 = 'Michael'.upper
upper2() # does the same thing as 'Michael'.upper() !
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!