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