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'}"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With