[Tutor] Poorly understood error involving class inheritance

christopher.henk at allisontransmission.com christopher.henk at allisontransmission.com
Thu Sep 10 22:59:36 CEST 2009


tutor-bounces+christopher.henk=allisontransmission.com at python.org wrote on 
09/10/2009 04:13:23 PM:

> I'm not sure why I'm getting an error at the end here:
> 
>  >>> class dummy:
> ...     def __init__(self,dur=0):
> ...             self.dur=dur
> ...
>  >>> z=dummy(3)
>  >>> z.dur
> 3
>  >>> z=dummy(dur=3)
>  >>> z.dur
> 3
> 
> That worked fine, of course.
> 
>  >>> class dummy2(str):
> ...     def __init__(self,dur=0):
> ...             self.dur=dur
> ...
>  >>> z=dummy2(3)
>  >>> z.dur
> 3
> 
> So far so good.  But:
> 
>  >>> z=dummy2(dur=3)
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> TypeError: 'dur' is an invalid keyword argument for this function
>  >>>
> 
> Why doesn't that last bit work?  I'm not sure where to begin to look 
> this up.
> Thanks!
> 
> --
> -dave----------------------------------------------------------------
> "Pseudo-colored pictures of a person's brain lighting up are
> undoubtedly more persuasive than a pattern of squiggles produced by a
> polygraph.  That could be a big problem if the goal is to get to the
> truth."  -Dr. Steven Hyman, Harvard
> 

I believe it has to do with the fact that str is immutable and thus should 
use __new__ instead of __init__. 
>>> class bob(str):
...     def __new__(self, fred=3):
...             self.fred=fred
...             return self
...
>>> george=bob()
>>> george.fred
3
>>> george=bob(fred=7)
>>> george.fred
7

Don't have a chance to read it now but maybe pep 253 explains it.
http://www.python.org/dev/peps/pep-0253/

Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090910/6ff0cd48/attachment.htm>


More information about the Tutor mailing list