Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are parentheses required around an integer to invoke methods on it? [duplicate]

Tags:

python

syntax

This does not work.

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

But this works.

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

Why are parentheses required around integer in order to invoke its methods? List or other data types don't seem to require it.

>>> [1, 2].__str__()
'[1, 2]'
>>> {'a': 'foo'}.__str__()
"{'a': 'foo'}"
like image 483
Lone Learner Avatar asked Feb 07 '23 22:02

Lone Learner


1 Answers

Per the python documentation, numeric literals require parentheses because otherwise it is unclear if . is denoting a floating point number or a method invocation.

For example, to invoke a method on an integer:

(10).__str__()

but not

10.__str__()

Whereas to invoke a method on a floating point number:

(10.).__str__()

or

10..__str__()

both work because the first . can only be a floating point indicator because it is followed by a . invoking the method.

like image 87
wogsland Avatar answered Feb 13 '23 04:02

wogsland