问题
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? :)
回答1:
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.
来源:https://stackoverflow.com/questions/5693942/subclassing-int-and-overriding-the-init-method-python