为什么超级.__ new__不需要论证,但实例.__ new__需要?

问题描述 投票:0回答:1

试图了解super__new__

这是我的代码:

class Base(object):
    def __new__(cls,foo):
        if cls is Base:
            if foo == 1:
                #  return Base.__new__(Child) complains not enough arguments
                return Base.__new__(Child,foo)
            if foo == 2:
                # how does this work without giving foo?
                return super(Base,cls).__new__(Child)  
        else:
            return super(Base,cls).__new__(cls,foo)

    def __init__(self,foo):
        pass 
class Child(Base):
    def __init__(self,foo):
        Base.__init__(self,foo)    
a = Base(1)  # returns instance of class Child
b = Base(2)  # returns instance of class Child
c = Base(3)  # returns instance of class Base
d = Child(1)  # returns instance of class Child

为什么super.__new__不需要争论而__new__需要它?

Python:2.7.11

python new-operator super
1个回答
1
投票

super().__new__Base.__new__的功能不同。 super().__new__object.__new__object.__new__不需要foo论证,但Base.__new__确实如此。

>>> Base.__new__
<function Base.__new__ at 0x000002243340A730>
>>> super(Base, Base).__new__
<built-in method __new__ of type object at 0x00007FF87AD89EC0>
>>> object.__new__
<built-in method __new__ of type object at 0x00007FF87AD89EC0>

你可能会感到困惑的是这一行:

return super(Base,cls).__new__(cls, foo)

这称为object.__new__(cls, foo)。这是正确的,它将foo论证传递给object.__new__,即使object.__new__不需要它。这在python 2中是允许的,但在python 3中会崩溃。最好从那里删除foo参数。

© www.soinside.com 2019 - 2024. All rights reserved.