[Tutor] The trap of the year

Karim karim.liateni at free.fr
Tue Jan 25 21:41:24 CET 2011


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




More information about the Tutor mailing list