Once __new__
in class Child
returns an instance of Child
, Child.__init__
will be called (with the same arguments __new__
was given) on that instance -- and apparently it just inherits Parent.__init__
, which does not take well to being called with just one arg (the other Parent
, A
).
If there is no other way a Child
can be made, you can define a Child.__init__
that accepts either one arg (which it ignores) or three (in which case it calls Parent.__init__
). But it's simpler to forego __new__
and have all the logic in Child.__init__
, just calling the Parent.__init__
appropriately!
To make this concrete with a code example:
class Parent(object):
def __init__(self, x, y, z):
print "INITIALIZING PARENT"
self.x = x
self.y = y
self.z = z
def __str__(self):
return "%s(%r, %r, %r)" % (self.__class__.__name__,
self.x, self.y, self.z)
class Child(Parent):
_sentinel = object()
def __init__(self, x, y=_sentinel, z=_sentinel):
print "INITIALIZING CHILD"
if y is self._sentinel and z is self._sentinel:
print "HIJACKING"
z = x.z; y = x.y; x = x.x
Parent.__init__(self, x, y, z)
print "CHILD IS DONE!"
p0 = Parent(1, 2, 3)
print p0
c1 = Child(p0)
print c1
c2 = Child(4, 5, 6)
print c2
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…