Python 为什么“超级”.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu?
试着去理解超新__ 下面是我的代码:Python 为什么“超级”.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu?,python,new-operator,super,Python,New Operator,Super,试着去理解超新__ 下面是我的代码: 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)
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
为什么“超级”.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
Python:2.7.11super.\uuuuuu new\uuuuuu与Base的函数不同。超级。新的是对象。新的。对象.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
这将调用对象。\uuuu new\uuuu cls,foo。没错,它将一个foo参数传递给object.\uuuuu new\uuuu,即使object.\uuuuu new\uuu不需要它。这在Python2中是允许的,但在Python3中会崩溃。最好从那里删除foo参数。原因与object相同。\uuuuu new\uuuuuu不需要foo而是Base。\uuu new\uuuuu需要。还有一个问题是,当子类定义在基之下时,我们如何在返回superBase cls时引用子对象。\uu new\uu Child?我的意思是,理想情况下,基地不应该在它的范围内有孩子,我想?那是因为超级拥有超级力量吗?@AnveshYalamarthy不,那不需要超级力量。这与为什么两个函数可以互相调用的原因相同,即使一个函数是在另一个函数之后定义的——在执行代码时,子类已经创建。如果在定义子类之前尝试a=Base1,那么确实会出现错误。
>>> 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)