What are the parentheses for at the end of Python

2020-02-05 06:10发布

问题:

I'm a beginner to Python and programming in general. Right now, I'm having trouble understanding the function of empty parentheses at the end of method names, built-in or user-created. For example, if I write:

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

...why is there an empty pair of parentheses after "upper?" Does it do anything? Is there a situation in which one would put something in there? Thanks!

回答1:

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


回答2:

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.



回答3:

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() !