Python: defaults arguments

Here is a funny snippet of code:

Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class foo:
...   def __init__(self, x=[]):
...     self.y = x
...
>>> a = foo()
>>> a.y.append("123456")
>>> a.y
['123456']
>>> b = foo()
>>> b.y
['123456']
>>> a.y.append("987654")
>>> a.y
['123456', '987654']
>>> b.y
['123456', '987654']

You better define foo as following:

>>> def foo():
>>>  def __init__(self, x=None):
>>>    if x is None: x = []
>>>    self.y = x

Tags: , ,

Leave a Reply