constructor overwrite

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Mon Feb 15 10:05:04 EST 2010


Mug a écrit :
> 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

With such an initializer, you'll have instances with an attribute 'y' 
and no attribute 'x', and instances with an attribute 'x' and no 
attribute 'y' :

 >>> class Obj(object):
...     def __init__(self, x=100, y=None):
...         if y is None: self.x = x
...         else: self.y = y
...
 >>> objx = Obj()
 >>> objx.x
100
 >>> objx.y
Traceback (most recent call last):
   File "<console>", line 1, in <module>
AttributeError: 'Obj' object has no attribute 'y'
 >>> objy = Obj(y='foo')
 >>> objy.x
Traceback (most recent call last):
   File "<console>", line 1, in <module>
AttributeError: 'Obj' object has no attribute 'x'
 >>> objy.y
'foo'
 >>>


Are you *sure* this is what you want ?

> 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

What else would you expect ???

> since x is not typed .

'x' is a name, and names are indeed "untyped". Now the object bound to 
name 'x' is actually typed.

> i am waiting for a result:
> objet = obj('not cool') #x=100 y='not cool'
> as they do in C++ or java.

Python is neither C++ nor Java (nor Pascal nor Lisp nor 
<yourfavoritelanguagehere> FWIW), so trying to forcefit C++/Java idioms 
will at best lead you to pain and frustation. Just like trying to 
forcefit Python idioms in C++ or Java (or Pascal or Lisp etc....).

> is there a way to do it?

objet = obj(y='not cool')

Now if you could explain the problem you're trying to solve instead of 
the solution you thought would solve it, we might eventually provide 
more help.



More information about the Python-list mailing list