【发布时间】:2020-10-10 15:49:01
【问题描述】:
class MyInt(int):
def __new__(cls, *args, **kwargs):
print(repr(args), repr(kwargs))
return super(MyInt, cls).__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
print(repr(args), repr(kwargs))
return super(MyInt, self).__init__(*args, **kwargs)
MyInt(1)
此代码输出:
(1,) {}
(1,) {}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-a45744cab1af> in <module>()
----> 1 MyInt(1)
<ipython-input-3-a38fc9aae2fe> in __init__(self, *args, **kwargs)
5 def __init__(self, *args, **kwargs):
6 print(repr(args), repr(kwargs))
----> 7 return super(MyInt, self).__init__(*args, **kwargs)
8
TypeError: object.__init__() takes no parameters
似乎基础__init__() 期待args,因为我可以打印它们。那么为什么我不能将它们传递给基类的方法呢? (顺便说一句,这在 python 2.7 中运行良好)
【问题讨论】:
-
int类实例是不可变的,因此它们的值由它们的__new__()设置,而不是它们的__init__()方法,它不接受参数——您可以更改或覆盖的东西。跨度> -
如果 __init__() 不接受参数,那么为什么我可以打印它们?另请参阅覆盖 int 的内置类 bool 的声明。 gist.github.com/grandquista/…
-
我的意思是“……你不能改变或覆盖的东西”。
-
好的,但是为什么
int将参数传递给我的自定义__init__()? -
是的,我就是这个意思。问题是
args没有被int识别,只是被向上传递给object.__init__(这会引发错误,而不是简单地忽略意外参数)。这就是为什么错误消息指的是object.__init__,而不是int.__init__。
标签: python python-3.x constructor int