Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing int and overriding the __init__ method - Python [duplicate]

Possible Duplicate:
inheritance from str or int

Hi folks,

I'm trying to subclass the int class without any success. Here is my attempt:

class SpecialInt(int):
    def __init__(self, x, base=10, important_text=''):
        int.__init__(self, x, base)
        self.important_text=important_text

If I perform the following:

integer = SpecialInt(123, 10, 'rage of the unicorns')

I get this error:

TypeRror: int() takes at most 2 arguments (3 given)

Any ideas? :)

like image 631
RadiantHex Avatar asked Sep 03 '25 16:09

RadiantHex


1 Answers

See __new__:

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

like image 154
robert Avatar answered Sep 05 '25 10:09

robert