为什么不是super .__ new__需要参数,而instance .__ new__需要参数呢?

时间:2019-03-06 08:44:22

标签: python new-operator super

试图了解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

1 个答案:

答案 0 :(得分: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参数。