Python int () overload

Let's say I have a base class in Python 3, which is some type of data type data type. I want to do this when I have an instance x of this class, I can call int (x) and call its conversion function to return the integer part.

I am sure it is simple, but I cannot figure out how to do it.

+6
source share
2 answers

You are redefining the __int__ magic method according to the example below ...

 class Test: def __init__(self, i): self.i = i def __int__(self): return self.i * 2 t = Test(5) print( int(t) ) # 10 
+13
source

Cancel the __int__() method.

+7
source

Source: https://habr.com/ru/post/920944/


All Articles