Python:为\uyu init扩展int和MRO__

2024-10-03 21:32:10 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我试图扩展内置的'int'类型。在这样做的时候,我想把一些keywoard参数传递给构造函数,所以我这样做:

class C(int):
     def __init__(self, val, **kwargs):
         super(C, self).__init__(val)
         # Do something with kwargs here...

然而,当调用C(3)时,C(3, a=4)给出:

^{pr2}$

并且C.__mro__返回预期的:

(<class '__main__.C'>, <type 'int'>, <type 'object'>)

但是Python似乎试图先调用int.__init__。。。有人知道为什么吗?这是翻译程序的问题吗?在


Tags: self类型initdeftypewithvaldo
3条回答

其他人(到目前为止)都说了些什么。Int是不可变的,因此必须使用new。在

另请参阅(接受的答案):

你应该压倒一切 "__new__",而不是{},因为int是不可变的。在

Python数据模型的文档建议使用__new__

object.new(cls[, ...])

^{bq}$

对于你所举的例子,应该这样做:

class C(int):

    def __new__(cls, val, **kwargs):
        inst = super(C, cls).__new__(cls, val)
        inst.a = kwargs.get('a', 0)
        return inst

相关问题 更多 >