gpt4 book ai didi

Python:为 __init__ 扩展 int 和 MRO

转载 作者:太空狗 更新时间:2023-10-29 18:27:06 25 4
gpt4 key购买 nike

在 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__...有人知道为什么吗?这是解释器中的错误吗?

最佳答案

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

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

new() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

对于您给出的示例,应该这样做:

class C(int):

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

关于Python:为 __init__ 扩展 int 和 MRO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1184337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com