Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does calling Python's 'magic method' not do type conversion like it would for the corresponding operator?

When I subtract a float from an integer (e.g. 1-2.0), Python does implicit type conversion (I think). But when I call what I thought was the same operation using the magic method __sub__, it suddenly does not anymore.

What am I missing here? When I overload operators for my own classes, is there a way around this other than explicitly casting input to whatever type I need?

a=1 a.__sub__(2.) # returns NotImplemented a.__rsub__(2.) # returns NotImplemented # yet, of course: a-2. # returns -1.0 
like image 296
doppler Avatar asked Feb 19 '19 22:02

doppler


People also ask

What is the purpose of the magic method __ init __?

The __init__ method for initialization is invoked without any call, when an instance of a class is created, like constructors in certain other programming languages such as C++, Java, C#, PHP etc. These methods are the reason we can add two strings with '+' operator without any explicit typecasting.

What is __ method __ in Python?

__call__ method is used to use the object as a method. __iter__ method is used to generate generator objects using the object.

What is __ INT __ in Python?

The __int__ method is called to implement the built-in int function. The __index__ method implements type conversion to an int when the object is used in a slice expression and the built-in hex , oct , and bin functions.


1 Answers

a - b isn't just a.__sub__(b). It also tries b.__rsub__(a) if a can't handle the operation, and in the 1 - 2. case, it's the float's __rsub__ that handles the operation.

>>> (2.).__rsub__(1) -1.0 

You ran a.__rsub__(2.), but that's the wrong __rsub__. You need the right-side operand's __rsub__, not the left-side operand.


There is no implicit type conversion built into the subtraction operator. float.__rsub__ has to handle ints manually. If you want type conversion in your own operator implementations, you'll have to handle that manually too.

like image 195
user2357112 supports Monica Avatar answered Oct 08 '22 19:10

user2357112 supports Monica