about __sub__() method for int

A forum for general discussion of the Python programming language.

about __sub__() method for int

Postby wenwenjinjin » Wed Oct 16, 2013 3:54 pm

Hi, I am a newbie to Python.
I have a weird question about Python.
Code: Select all
>>>a=5
>>>a.__sub__(1)
4
>>>5.__sub__(1)
SyntaxError


I know the interger 5 is an object of type int. How come I can not directly call its own method?
Last edited by stranac on Wed Oct 16, 2013 4:18 pm, edited 1 time in total.
Reason: Locked. Added code tags.
wenwenjinjin
 
Posts: 1
Joined: Wed Oct 16, 2013 3:43 pm

Re: about __sub__() method for int

Postby stranac » Wed Oct 16, 2013 4:21 pm

That's because python sees 5. and expects it to be a floating point number.
Therefor, anything other than numbers is not allowed, and results in a SyntaxError.

You can do it like this:
Code: Select all
(5).__sub__(1)
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1114
Joined: Thu Feb 07, 2013 3:42 pm


Return to General Discussions

Who is online

Users browsing this forum: No registered users and 3 guests