[Tutor] The trap of the year

Alan Gauld alan.gauld at btinternet.com
Wed Jan 26 01:30:05 CET 2011


"Karim" <karim.liateni at free.fr> wrote

> 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.

Yes that is a feature of Pythons default argument mechanism.
It has been discussed many times on this list and in the docs.
As you discovered the best way to avoid it is use None as the
default then create a new list inside the function if it is None.

> I never see warning about this fact in any books before.

Its quite commonly warned against but until you get bitten
the significance just passes you by! I bet if you look out for
it now you'll see it often ebnough!

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list