How to add a constructor to a subclassed numeric type?
<p>I want to subclass a numeric type (say, int) in python and give it a shiny complex constructor. Something like this:</p>

<pre><code>class NamedInteger(int):
    def __init__(self, value):
        super(NamedInteger, self).__init__(value)
        self.name = 'pony'

    def __str__(self):
        return self.name

x = NamedInteger(5)
print x + 3
print str(x)
</code></pre>

<p>This works fine under Python 2.4, but Python 2.6 gives a deprecation warning. What is the best way to subclass a numeric type and to redefine constructors for builtin types in newer Python versions?</p>

<p>Edit:
Spotted in comments that this works without a super() line, so it could be like this:</p>

<pre><code>class NamedInteger(int):
    def __init__(self, value):
        self.name = 'pony'

    def __str__(self):
        return self.name

x = NamedInteger(5)
print x + 3
print str(x)
</code></pre>

<p>I believe that this works because int is immutable type and has only <code>__new__</code> method. However I would be glad to know a correct way of subclassing, so I could build a class with behaviour like this:</p>

<pre><code>x = NamedInteger(5, 'kitty')
</code></pre>

<p>Second edit:</p>

<p>The final version now looks like this:</p>

<pre><code>class NamedInteger(int):
    def __new__(cls, value, name='pony'):
        self = super(NamedInteger, cls).__new__(cls, value)
        self.name = name
        return self

    def __str__(self):
        return self.name

x = NamedInteger(5)
y = NamedInteger(3, 'kitty')
print "%d %d" % (x, y)
print "%s %s" % (x, y)
</code></pre>

<p>Answers below also gave very interesting links to <a href="http://docs.python.org/library/abc.html" rel="nofollow">Abstract Base Classes</a> and <a href="http://docs.python.org/library/numbers.html#module-numbers" rel="nofollow">numbers</a> modules.</p>
