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

爷,独闯天下 提交于 2021-02-05 06:00:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!