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