在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)
给出:
并且C.__mro__
返回预期的:
(<class '__main__.C'>, <type 'int'>, <type 'object'>)
但是Python似乎试图先调用int.__init__
。。。有人知道为什么吗?这是翻译程序的问题吗?在
其他人(到目前为止)都说了些什么。Int是不可变的,因此必须使用new。在
另请参阅(接受的答案):
你应该压倒一切},因为int是不可变的。在
"__new__"
,而不是{Python数据模型的文档建议使用
__new__
:object.new(cls[, ...])
^{bq}$对于你所举的例子,应该这样做:
相关问题 更多 >
编程相关推荐