Python:为 __init__ 扩展 int 和 MRO
在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)
code> 给出:
'a' is an invalid keyword argument for this function`
并且 C.__mro__
返回预期的:
(<class '__main__.C'>, <type 'int'>, <type 'object'>)
但似乎 Python 试图首先调用 int.__init__
...有人知道为什么吗? 这是解释器中的错误吗?
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...
However while calling C(3)
works fine, C(3, a=4)
gives:
'a' is an invalid keyword argument for this function`
and C.__mro__
returns the expected:
(<class '__main__.C'>, <type 'int'>, <type 'object'>)
But it seems that Python is trying to call int.__init__
first... Anyone know why? Is this a bug in the interpreter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Python 数据模型的文档建议使用
__new__
:object .新(cls[, ...])
对于您给出的示例,应该执行类似的操作:
The docs for the Python data model advise using
__new__
:object.new(cls[, ...])
Something like this should do it for the example you gave:
你应该压倒一切
"__new__"
,而不是"__init__"
,因为整数是不可变的。You should be overriding
"__new__"
, not"__init__"
as ints are immutable.其他人(到目前为止)所说的。 Int 是不可变的,所以你必须使用new。
另请参阅(已接受的答案):
What everyone else (so far) said. Int are immutable, so you have to use new.
Also see (the accepted answers to):