constructor overwrite

Steve Holden steve at holdenweb.com
Mon Feb 15 09:58:19 EST 2010


Mug wrote:
> hi ,i had a problem on constructor overwrite:
> i have something like:
> 
> class obj:
> def __init__(self, x=100, y=None):
>     if y is None:
>           self.x=x
>     else:
>           self.y=y
> so i can call :
> objet = obj()  # x=100 y=None
> or
> objet = obj(40) # x= 40 y=None
> 
> but if i do :
> objet = obj('not cool') #x='not cool' y=None
> since x is not typed .
> 
> i am waiting for a result:
> objet = obj('not cool') #x=100 y='not cool'
> as they do in C++ or java.
> is there a way to do it?
> thanks

You could check the type(s) of the argument(s) in your code, if you
want, but Python does not support signature analysis, dynamic method
dispatch or static typing. You can do

object = obj("y='not cool')

but I doubt this is what you want. Your post raises a couple of thier
points.

First, __init__ is *not* the constructor. By the time it is called
creation of the new object is already complete, and __init__() (as its
name suggests) merely initializes it. In Python 2's "new-style" classes,
and in Python 3, construction is performed by the class's __new__() method.

Secondly, it seems a little strange that you are happy to create
different instances, in some of which self.y is not initialized and in
others self.x is not initialized. You may have a good reason for doing
this, I merely point it out as a potential cause of AttributeError
exceptions.

regards
 Steve

regards
 Steve

-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC                 http://www.holdenweb.com/
UPCOMING EVENTS:        http://holdenweb.eventbrite.com/




More information about the Python-list mailing list