views:

94

answers:

1

I'm interested in subclassing the built-in int type in Python (I'm using v. 2.5), but having some trouble getting the initialization working.

Here's some example code, which should be fairly obvious.

class TestClass(int):
    def __init__(self):
        int.__init__(self, 5)

However, when I try to use this I get:

>>> a = TestClass()
>>> a
0

where I'd expect the result to be 5.

What am I doing wrong? Google, so far, hasn't been very helpful, but I'm not really sure what I should be searching for

+10  A: 

int is immutable so you can't modify it after they are created, use __new__ instead

class TestClass(int):

    def __new__(cls, *args, **kwargs):
        inst = super(TestClass, cls).__new__(cls, 5)

        return inst

print TestClass()
Anurag Uniyal