为什么 Python 新式类中的 __new__ 不是类方法?
Python 2.2 的变更日志(引入了新样式类)对 __new__
函数进行了以下说明:
__new__
是静态方法,而不是类方法。我最初认为它必须是一个类方法,这就是我添加classmethod
原语的原因。不幸的是,对于类方法,向上调用在这种情况下无法正常工作,因此我必须将其设为静态方法,并将显式类作为其第一个参数。
但是,我想不出为什么类方法不能用于此目的,而且它肯定看起来会更好。为什么__new__
最终没有成为类方法?当 Guido 说“在这种情况下向上调用不起作用”时,他指的是什么?
The Changelog for Python 2.2 (where new-style classes were introduced) says the following about the __new__
function:
__new__
is a static method, not a class method. I initially thought it would have to be a class method, and that's why I added theclassmethod
primitive. Unfortunately, with class methods, upcalls don't work right in this case, so I had to make it a static method with an explicit class as its first argument.
However, I cannot think of why class methods wouldn't work for this purpose, and it would certainly look better. Why didn't __new__
end up as a class method in the end? What does Guido refer to when he says that "upcalls don't work right in this case"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
__new__
是静态方法,当您在其中创建子类的实例时,允许使用用例:的写法为:
如果
new
是一个类方法,则上面 没有地方放置subcls
。更常见的情况是调用父级
__new__
而不使用super()
。 在这种情况下,您需要一个地方来显式传递cls
:__new__
being static method allows a use-case when you create an instance of a subclass in it:If
new
is a class method then the above is written as:and there is no place to put
subcls
.A more common case would be to call parent
__new__
without usingsuper()
. You need a place to passcls
explicitly in this case: