views:

273

answers:

3

Given is the following 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, which acts as an integer (or float). So I want to do the followng things:

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

The first statement print int(f)+5 is working, cause there are two integers. The second one is failing, because I have to implement __add__ to do this operation with my class.

So to implement the integer behaviour, I have to implement all the integer emulating methods. How could I get around this. I tried to inherit from int, but this attempt was not successful.

Update

Inheriting from int fails, if you want to use a __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 then call:

f=Foo(some_argument=3)

you get:

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

Tested with Python 2.5 and 2.6

+6  A: 

In Python 2.4+ inheriting from int works:

class MyInt(int):pass
f=MyInt(3)
assert f + 5 == 8
Heikki Toivonen
I had problems when I was using named arguments for the constructor (__init__). When I call f=MyInt(other_argument=True) it was failing (TypeError: 'other_argument' is an invalid keyword argument for this function)
Günther Jehle
@Günther Jehle: Please add this to your question. This comment doesn't square with your question, and doesn't make a lot of sense in the context of this question. Please update the question to include all the facts.
S.Lott
added the result of inheriting from int
Günther Jehle
A: 

Try to use an up-to-date version of python. Your code works in 2.6.1.

jdb
I will give this a try
Günther Jehle
My python version is currently 2.5.1
Günther Jehle
Wait, why are you inheriting from `object` ??The code works if you inherit from `int`.
jdb
+1  A: 

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

Now your class work 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 about overriding new can be found in Unifying types and classes in Python 2.2.

Pär Wieslander