继承int类并重写__init__方法 - Python

4

可能是重复问题:
从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')

I get this error:

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

有什么想法吗? :)

重复。请参见此处:https://dev59.com/qnE85IYBdhLWcg3wqVT4 - user2665694
请参见 https://dev59.com/l3A75IYBdhLWcg3wipqH - Achim
https://dev59.com/l3A75IYBdhLWcg3wipqH - Marijn van Vliet
1个回答

9

请参考__new__

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接