Python:为__init__扩展int和MRO [英] Python: extending int and MRO for __init__
问题描述
在Python中,我试图扩展内置的'int'类型.为此,我想将一些关键参数传递给构造函数,所以我要这样做:
In Python, I'm trying to extend the builtin 'int' type. In doing so I want to pass in some keywoard arguments to the constructor, so I do this:
class C(int):
def __init__(self, val, **kwargs):
super(C, self).__init__(val)
# Do something with kwargs here...
但是,调用C(3)
可以正常工作时,C(3, a=4)
给出:
However while calling C(3)
works fine, C(3, a=4)
gives:
'a' is an invalid keyword argument for this function`
和C.__mro__
返回预期的结果:
(<class '__main__.C'>, <type 'int'>, <type 'object'>)
但是似乎Python试图先调用int.__init__
...有人知道为什么吗?这是解释器中的错误吗?
But it seems that Python is trying to call int.__init__
first... Anyone know why? Is this a bug in the interpreter?
推荐答案
Python数据模型的文档建议使用__new__
:
The docs for the Python data model advise using __new__
:
object.new(cls[, ...])
新()主要用于允许不可变类型(如int,str或tuple)的子类自定义实例创建.为了自定义类的创建,通常也将其覆盖在自定义元类中.
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.
对于您给出的示例,应该执行以下操作:
Something like this should do it for the example you gave:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!