constructors in python

Jeff Shannon jeff at ccvcorp.com
Mon Apr 22 15:45:33 EDT 2002


In article <a9usk3$rk$1 at news.iucc.ac.il>, elimli at yahoo.com 
says...
> But what does happened when I forget (I'm just a man) to call father's c-or?
> Semi-initialized object? C++ doesn't permit not to call the base c-or.
 
The semantics are different between C++'s constructors and 
Python's __init__() methods.

In the C++ case, the constructor is called to allocate memory for 
the object, and create an initial layout in that memory.  If the 
constructor fails, then you have no object.

In Python, the object is fully created *before* __init__() is 
called.  Thus, __init__() is more of an initializer than a 
constructor.  The equivalent C++ idiom would be something like 
this:

    foo = new foo_obj();
    foo.init();

...with the __init__() method corresponding to the foo.init() 
call, and the new being done internally by the interpreter.  If 
your __init__() method fails, then you still have an object, 
even though it is an incompletely initialized one.

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list