[Tutor] : unexpected behavior with assignment in __init__

Orri Ganel singingxduck at gmail.com
Wed Jan 25 12:35:15 CET 2006

Kent Johnson wrote:

>variable, it has no effect outside the method; inside a method, self is 
>just a method parameter, nothing more. There is some magic that gives 
>self its value for the call.
>When __init__() is called the new instance has already been created, you 
>are just initializing its state, not creating the object. You can do 
>what you want by defining stime.__new__(). __new__() is responsible for 
>actually creating a new object. You still have to check for an stime 
>instance in __init__() because __init__() will be called even when 
>__new__() returns an existing instance.
>Here is a simplified example:
>  >>> class stime(object):
>  ...   def __new__(cls, value):
>  ...     if isinstance(value, cls):
>  ...       return value
>  ...     return object.__new__(cls, value)
>  ...   def __init__(self, value):
>  ...     print 'stime.__init__', value
>  ...     if isinstance(value, stime):
>  ...       return
>  ...     self.value = value
>  ...
>  >>> a=stime(3)
>stime.__init__ 3
>  >>> a
><__main__.stime object at 0x00A32E90>
>  >>> b=stime(a)
>stime.__init__ <__main__.stime object at 0x00A32E90>
>  >>> b
><__main__.stime object at 0x00A32E90>
>  >>> a.value
>  >>> b.value
>  >>> a is b
> Assigning to self in __init__() just changes the value of the local

Thanks.  I think I've run into this sort of behavior before, but didn't 
remember the details well enough to remember the solution (if I've ever 
known it).  Hopefully this'll be the last of me emails to the Tutor 
mailing list on this particular problem. ;-)

Thanks again,

Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060125/4bdbfe44/attachment.html 

More information about the Tutor mailing list