【问题标题】:What are the parentheses for at the end of Python method names? [duplicate]Python 方法名称末尾的括号是什么? [复制]
【发布时间】:2015-11-14 17:37:14
【问题描述】:

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

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

...为什么“upper”后面有一对空括号?它有什么作用吗?有没有一种情况可以放东西进去?谢谢!

【问题讨论】:

标签: python class methods parentheses


【解决方案1】:

upper() 是一个命令 要求运行上层方法,而upper 是一个引用 方法本身。例如,

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

【讨论】:

    【解决方案2】:

    括号表示你要调用的方法

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

    如果你只是说upper,那么它返回的是一个方法,而不是你应用方法时得到的值

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

    【讨论】:

      【解决方案3】:

      因为没有你只是引用了方法对象。 你告诉 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 文档中明确列为单独的表达式类型:

      call 调用一个可调用对象(例如,函数),其中可能包含一系列空的 参数

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-23
        • 2013-02-25
        • 2011-11-02
        • 2017-10-27
        • 1970-01-01
        • 2015-08-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多