On Tue, 22 Jul 2008 09:35:58 -0700, Matimus wrote:
On Jul 22, 9:26 am, Catherine Heathcote
<catherine.heat hc...@gmail.com wrote:
>If I create a new class inherited from another with a constructor, what
>happens with the new class's constructer?
>Thanks for your time.
>
Nothing, unless you call it in your constructor.
>
class Base(object):
def __init__(self):
print "Base constructor called"
>
# without calling the base class constructor
class C(Base):
def __init__(self):
print "C constructor called"
>
# call the base class constructor using super
class D(Base):
def __init__(self):
super(D, self).__init__( )
print "D constructor called"
>
c = C()
d = D()
>
>
Matt
Aha! Makes sence, thankyou. As you can probably tell I am new to Python,
but not programming as a whole.
since it's an ordinary method call, you don't have to initialize the
parent the first thing you do. you can also pass in any arguments you
want (including arguments passed to the child constructor):
>>class OtherChild(Othe rParent):
.... def __init__(self, a, b, c):
.... self.c = c
.... OtherParent.__i nit__(self, a + b)
....
there's even a common pattern for passing along *all* arguments, no
matter what they are:
>>class OtherChild(Othe rParent):
.... def __init__(self, *args, **kwargs):
.... # do something here
.... OtherParent.__i nit__(self, *args, **kwargs)
.... # do something else here
....
instead of explicitly naming the baseclass, you can use the "super"
method to automatically look up the parent class, but this only works
if the parent class inherits from "object" or a subclass thereof:
>If I create a new class inherited from another with a constructor, what
>happens with the new class's constructer?
Python doesn't really have constructors; when you create an object,
Python first creates the object and then calls the __init__ method, if
available
To elaborate a bit on Fredrik's response, there is a sense in which
Python has constructors, but, to the extent it does, a constructor is
the __new__, __init__ pair. For immutables, everything happens in
__new__, for mutables, most things happen in the __init__ chain.
Comment