what is happening at __init__
Eric Brunel
eric.brunel at pragmadev.com
Mon Mar 4 08:42:21 EST 2002
Hi,
Your questions regarding the so-called "constructor" may simply show that
the term "constructor" is not so good after all. In fact, the constructor
does not "build" anything: the instance is already created (i.e. allocated
in the memory) when the constructor is called. So your Q2 starts on the
wrong basis: self is *not* assigned to a new value within the function; the
new value is created *before* the call to the constructor, which simply
references it as its parameter named "self", just like any other
function/method. So if you do something like:
class C:
def __init__(self):
self = None
o = C()
o will *not* be set to None, but to a new, uninitialized instance of C: as
always in Python, modifications to a method parameter are lost when the
method ends, and the "constructor" is no exception.
In fact, Python is a tad more explicit than other languages when it calls
the "constructor" __init__, because it would be far more accurate to call
it an "initializer" rather than a "constructor": it doesn't create the
instance, but simply initialize its attributes. And note it is not specific
to Python: in C++ or in Java, the "constructor" is also called when the
instance has already been allocated, so it doesn't build it.
Maybe this enlightens you a little bit more. The answers for your other
questions should now be clear:
- Q1 is a "yes but": instance is created, then passed to the constructor
where it is assigned to local variable "self"
- Q2 is pointless: self is *not* assigned in the constructor
- Q3 is no: the return value for the constructor is completely ignored, so
you can return whatever you want (it's just useless...)
- Q4 is yes: you work on the actual instance that was created before the
call to the constructor
- Q5 is yes: it is not the return value of the constructor that matters,
but what is done to self's attributes within the method
If there are still unclear points in all that, you should carefully read
the section 3.1 of the Python language reference manual ("Objects, values
and types") where the objects and references concepts are described (IMHO
not so well, but it's a start...).
HTH
- eric -
More information about the Python-list
mailing list