Python:扩展int并设置__init__的MRO

10 投票
3 回答
1956 浏览
提问于 2025-04-15 13:10

在Python中,我想扩展内置的'int'类型。在这个过程中,我想在构造函数中传入一些关键字参数,所以我这样做:

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

但是,当我调用C(3)时一切正常,而C(3, a=4)却出现了:

'a' is an invalid keyword argument for this function` 

C.__mro__返回了预期的结果:

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

但看起来Python似乎是先尝试调用int.__init__... 有人知道这是为什么吗?这是解释器的一个bug吗?

3 个回答

3

你应该重写 "__new__",而不是 "__init__",因为整数是不可变的。

3

大家到目前为止说的都是一样的。整数(Int)是不可变的,所以你必须使用new

另外可以看看(被接受的答案):

7

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

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

new() 主要是为了让不可变类型的子类(比如 int、str 或 tuple)能够自定义实例的创建。它也常常在自定义元类中被重写,以便定制类的创建过程。

对于你给出的例子,像这样应该就可以了:

class C(int):

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

撰写回答