[Tutor] Question on implmenting __getitem__ on custom classes

Arup Rakshit ar at zeit.io
Tue Apr 23 10:57:15 EDT 2019


On 23/04/19 3:40 PM, Steven D'Aprano wrote:
> Watch out here, you have a mutable default value, that probably doesn't
> work the way you expect. The default value is created ONCE, and then
> shared, so if you do this:
>
> a = MyCustomList()  # Use the default list.
> b = MyCustomList()  # Shares the same default list!
> a.append(1)
> print(b.list)
> # prints [1]
>
> You probably want:
>
>       def __init__(self, list=None):
>           if list is None:
>               list = []
>           self.list = list

That is really a new thing to me. I didn't know. Why list=None in the 
parameter list is different than in the body of __init__ method? Can you 
elaborate this?

-- 
Thanks,

Arup Rakshit



More information about the Tutor mailing list