", line 1 10.__str__() ^ SyntaxEr...">

Why do parentheses need an integer to call methods on it?

This does not work.

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

But it does work.

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

Why do we need parentheses around an integer to call its methods? A list or other data types do not seem to require this.

>>> [1, 2].__str__()
'[1, 2]'
>>> {'a': 'foo'}.__str__()
"{'a': 'foo'}"
+4
source share
1 answer

In the python documentation, numeric literals require brackets, because otherwise it is not clear whether .the floating point number or method call means .

For example, to call a method for an integer:

(10).__str__()

but not

10.__str__()

While calling the floating point method:

(10.).__str__()

or

10..__str__()

, . , . .

+7

Source: https://habr.com/ru/post/1625595/


All Articles