【问题标题】:Why are parentheses required around an integer to invoke methods on it? [duplicate]为什么在整数周围需要括号才能调用它的方法? [复制]
【发布时间】:2016-01-23 02:36:14
【问题描述】:

这不起作用。

>>> 10.__str__()
  File "<stdin>", line 1
    10.__str__()
             ^
SyntaxError: invalid syntax

但这行得通。

>>> (10).__str__()
'10'

为什么要在整数周围加上括号才能调用它的方法?列表或其他数据类型似乎不需要它。

>>> [1, 2].__str__()
'[1, 2]'
>>> {'a': 'foo'}.__str__()
"{'a': 'foo'}"

【问题讨论】:

    标签: python syntax


    【解决方案1】:

    根据python documentation,数字文字需要括号,否则不清楚. 是表示浮点数还是方法调用。

    例如,在整数上调用方法:

    (10).__str__()
    

    但不是

    10.__str__()
    

    而在浮点数上调用方法:

    (10.).__str__()
    

    10..__str__()
    

    两者都有效,因为第一个 . 只能是浮点指示符,因为它后面跟着一个调用该方法的 .

    【讨论】:

    • 非常有趣:10..__str__().
    • @Chris:因为10. 给出了10.0,这是一个浮点对象。所以10..__str__() == 10.0.__str__().
    • @KevinGuan,是的,我打算以这个为例,而不是要求澄清。
    • @Chris 谢谢!我已将您的示例添加到我的答案中,因为它确实有助于澄清问题。
    猜你喜欢
    • 2015-11-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 2015-08-09
    • 2018-06-24
    • 2021-05-23
    • 2011-08-14
    相关资源
    最近更新 更多