Dav*_*ell 4 python methods class parentheses
我是Python和编程的初学者.现在,我无法理解方法名称末尾,内置或用户创建的空括号的功能.例如,如果我写:
print "This string will now be uppercase".upper()
Run Code Online (Sandbox Code Playgroud)
...为什么在"鞋帮"后面有一对空括号?它有什么用吗?有没有人会把东西放在那里的情况?谢谢!
因为没有那些,你只是引用方法对象.有了它们,你告诉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'
Run Code Online (Sandbox Code Playgroud)
这里get_uppercase存储对str.upper字符串的绑定方法的引用.只有当我们()在引用之后再添加实际调用的方法时.
这个方法在这里没有参数没有区别.您仍然需要告诉Python进行实际调用.
(...)然后,该部分称为Call表达式,在Python文档中显式列为单独的表达式:
一个电话调用可调用对象(如函数)有可能是空的一系列参数.
括号表示您要调用该方法
upper() 返回应用于字符串的方法的值
如果你只是说upper,那么它返回一个方法,而不是应用该方法时获得的值
>>> print "This string will now be uppercase".upper
<built-in method upper of str object at 0x7ff41585fe40>
>>>
Run Code Online (Sandbox Code Playgroud)