为什么 super.__new__ 不需要参数但 instance.__new__ 需要?
Why doesn't super.__new__ need argument but instance.__new__ needs?
试图理解 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
参数。
试图理解 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
参数。