Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Class with integer emulation

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 following 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

like image 281
Günther Jena Avatar asked Oct 28 '09 16:10

Günther Jena


People also ask

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.

What is __ class __ in Python?

__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .

What is __ call __ Python?

__call__ in Python Python has a set of built-in methods and __call__ is one of them. The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function.

What does __ add __ do in Python?

__add__ magic method is used to add the attributes of the class instance. For example, let's say object1 is an instance of a class A and object2 is an instance of class B and both of these classes have an attribute called 'a', that holds an integer.


1 Answers

In Python 2.4+ inheriting from int works:

class MyInt(int):pass
f=MyInt(3)
assert f + 5 == 8
like image 200
Heikki Toivonen Avatar answered Oct 03 '22 17:10

Heikki Toivonen