Python class with integer emulation

The following is an example:

class Foo(object): def __init__(self, value=0): self.value=value def __int__(self): return self.value 

I want to have a class Foo that acts as an integer (or float). So I want to do the following:

 f=Foo(3) print int(f)+5 # is working print f+5 # TypeError: unsupported operand type(s) for +: 'Foo' and 'int' 

The first print int(f)+5 statement works because there are two integers. The second error, because I have to implement __add__ to perform this operation with my class.

So, in order to implement integer behavior, I have to implement all methods for emulating an integer. How could I get around this. I tried to inherit from int , but this attempt was not successful.

Update

Inheritance from int fails if you want to use __init__ :

 class Foo(int): def __init__(self, some_argument=None, value=0): self.value=value # do some stuff def __int__(self): return int(self.value) 

If you call:

 f=Foo(some_argument=3) 

You are getting:

 TypeError: 'some_argument' is an invalid keyword argument for this function 

Tested with Python 2.5 and 2.6

+5
source share
3 answers

You need to override __new__ , not __init__ :

 class Foo(int): def __new__(cls, some_argument=None, value=0): i = int.__new__(cls, value) i._some_argument = some_argument return i def print_some_argument(self): print self._some_argument 

Your class now works as expected:

 >>> f = Foo(some_argument="I am a customized int", value=10) >>> f 10 >>> f + 8 18 >>> f * 0.25 2.5 >>> f.print_some_argument() I am a customized int 

More information on overriding new can be found in Combining Types and Classes in Python 2.2 .

+5
source

In Python 2.4+, inheritance from int works:

 class MyInt(int):pass f=MyInt(3) assert f + 5 == 8 
+7
source

Try using an updated version of python. Your code works in 2.6.1.

+2
source

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


All Articles