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
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
source share