Helpful Information
 
 
Category: Python
Python absolute newbie question

Hi
I wanted to verify that number literals are objects in Python as they are in Ruby, so I typed in dir(1) at the console.

As I understand it, the + operator is actually calling __add__ behind the scenes.

If that's right, is there any particular reason why 1.__add__(2) doesn't work?

Apologies if this is a little basic!

Hi
I wanted to verify that number literals are objects in Python as they are in Ruby, so I typed in dir(1) at the console.

As I understand it, the + operator is actually calling __add__ behind the scenes.

If that's right, is there any particular reason why 1.__add__(2) doesn't work?

Apologies if this is a little basic!
python is pure oop. the reason why 1.__add__(2) don't work is that the interpreter don't know what type is 1. try this:


one = 1
one.__add__(2)


best regards

Thank you for the reply.

What confuses me is that 1.2.__add__(2) does work. :confused:

in 1.2, it thinks that 2 is a property of one (i think, im a python newb too)

what does it return? 4? 2? 3.2?

This works.

int(1).__add__(2)

So maybe the interpreter needs to know that 1 is an integer. Same result with:

n = 1
n.__add__(2)

If 1.2.__add__(2) works, maybe that's because the presence of the "." automatically makes 1.2 a float, while simply "1" may be confused with a boolean? Dunno, but it seems to make sense. :)










privacy (GDPR)