3

可能重复:
从 str 或 int 继承

嗨伙计,

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

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

如果我执行以下操作:

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

我收到此错误:

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

有任何想法吗?:)

4

1 回答 1

6

__new__

__new__() 主要是为了允许不可变类型(如 int、str 或 tuple)的子类自定义实例创建。它也通常在自定义元类中被覆盖,以自定义类创建。

于 2011-04-17T14:04:18.997 回答