[Tutor] The trap of the year

Karim karim.liateni at free.fr
Tue Jan 25 22:16:59 CET 2011


If I understand a little bit what happen in:

def __init__(self, parameters=[]):
    [...]

The list argument is built before instance creation and indeed 
constructor execution.
So this is the same list instance of constructor parameter for all new 
instance creation.

For me it was a bad surprise!
I never see warning about this fact in any books before.

Regards
Karim

On 01/25/2011 10:08 PM, Izz ad-Din Ruhulessin wrote:
> Or the internal memory id or whatever it's called.
>
> 2011/1/25 Izz ad-Din Ruhulessin <izzaddin.ruhulessin at gmail.com 
> <mailto:izzaddin.ruhulessin at gmail.com>>
>
>     I think it has something to do with the physical id of the object
>
>     2011/1/25 Karim <karim.liateni at free.fr
>     <mailto:karim.liateni at free.fr>>
>
>
>         Hello All,
>
>         Just to share on rageous bug I encounter where 2 lists which
>         "should" to be different (same id) because hold by different
>         instances of the same class are not in fact DIFFERENT, see below:
>
>         >>> class Device():
>         ...     def __init__(self, parameters=[]):
>         ...         self.parameters = parameters
>         ...     def param(self):
>         ...         print(id(self.parameters))
>         ...
>         >>> a=Device()
>         >>> b=Device()
>         >>> a.param()
>         140559202956568
>         >>> b.param()
>         140559202956568
>
>         When I discovered that I was puzzled because at the prompt:
>
>         >>> a = []
>         >>> b = []
>         >>> id(a)
>         140559202956496
>         >>> id(b)
>         140559202957000
>
>         I am not really understanding why my init in the class made it
>         refers to the same list object.
>         What is the difference with 2nd example directly at the prompt?
>
>         By the way, this one is ok:
>
>         >>> class Device():
>         ...     def __init__(self,parameters=None):
>         ...         self.parameters = None
>         ...         self.parameters = []
>         ...     def param(self):
>         ...         print(id(self.parameters))
>         ...
>         >>> a=Device()
>         >>> b=Device()
>         >>> b.param()
>         140559202956496
>         >>> a.param()
>         140559202956568
>
>         Karim
>
>
>         _______________________________________________
>         Tutor maillist  - Tutor at python.org <mailto:Tutor at python.org>
>         To unsubscribe or change subscription options:
>         http://mail.python.org/mailman/listinfo/tutor
>
>
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110125/4847debb/attachment.html>


More information about the Tutor mailing list