对int进行子类化并重写__init__方法 - Python

Rad*_*Hex 3 python int built-in subclassing

可能重复:
从str或int继承

嗨伙计,

我试图继承int类没有任何成功.这是我的尝试:

class SpecialInt(int):
    def __init__(self, x, base=10, important_text=''):
        int.__init__(self, x, base)
        self.important_text=important_text
Run Code Online (Sandbox Code Playgroud)

如果我执行以下操作:

integer = SpecialInt(123, 10, 'rage of the unicorns')
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

TypeRror: int() takes at most 2 arguments (3 given)
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?:)

rob*_*ert 6

__new__:

__new__()主要用于允许不可变类型的子类(如int,str或tuple)自定义实例创建.它也通常在自定义元类中重写,以自定义类创建.