constructor list slice confusion

Simon Morgan me at privacy.net
Thu Jul 14 04:28:36 EDT 2005


On Thu, 14 Jul 2005 08:38:36 +0200, Peter Otten wrote:

> Maybe, after a little renaming you can see it yourself:
> 
> class SomeClass:
>     def __init__(self, default_contents=[]):
>         # make a copy of default_contents that is # kept in a SomeClass
>         instance
>         self.contents = default_contents[:]
>     def add(self, element):
>         # modify the *copy* of default_contents...
>         self.contents.append(element)

Aha, I think I get it now. default_contents will always be an empty list
because before anything is added to it, a copy is made.

I think I was focusing too hard on the constructor. :)

Thanks for your help.




More information about the Python-list mailing list