Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: __add__ and +, different behavior with float and integer

When adding an integer value to a float value, I realized that __add__ method is working fine if called on float, such as this:

>>> n = 2.0
>>> m = 1
>>> n.__add__(m)
3.0

but not if called on an integer:

>>> m.__add__(n)
NotImplemented

At first I thought that __add__ was just being implemented differently for int and float types (like float types accepting to be added to int types, but not the opposite). Then I noticed that everything works fine if I use the + operator instead:

>>> n + m
3.0
>>> m + n
3.0

Does anybody know why this is happening? Are __add__ and + not deeply related to each other?

like image 336
Gianluca John Massimiani Avatar asked Jul 27 '16 22:07

Gianluca John Massimiani


People also ask

What is the difference between integers and floats in Python?

Numbers in Python exist in two chief forms: integers and floats. As noted in Lesson 02 , integers are numbers without a decimal point, whereas floats are numbers with a decimal point. This is am important distinction that you MUST remember, especially when working with data imported from and exported to Excel.

How does float() work with Python?

Example: How does float () work with Python? Float () is a method that returns a floating-point number for a provided number or string. Float () returns the value based on the argument or parameter value that is being passed to it. If no value or blank parameter is passed, it will return the values 0.0 as the floating-point output.

How do you convert a float to an int in Python?

Python has built-in methods for converting between integers and floats. You can convert any decimal number, octal, hexadecimal or string to an int by using the int () function. For example: Float represents real numbers, a data type that is used to define floating decimal points.

How to create various types of integers in Python?

This is how you would create various integers in Python: In Python 3 there are no different integer types as in Python 2.7, which has int and long int. In Python 3 there is only one integer type, which can store very large numbers. For example: Python has built-in methods for converting between integers and floats.


1 Answers

a + b does not directly translate to a.__add__(b). It also tries b.__radd__(a) if a.__add__ doesn't exist or returns NotImplemented, or if b is an instance of a subtype of a's type.

like image 59
user2357112 supports Monica Avatar answered Oct 30 '22 17:10

user2357112 supports Monica