[Tutor] Question on implmenting __getitem__ on custom classes
Steven D'Aprano
steve at pearwood.info
Tue Apr 23 12:38:54 EDT 2019
On Tue, Apr 23, 2019 at 08:27:15PM +0530, Arup Rakshit wrote:
> >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?
Try running this code and see what happens:
def make_default():
print("creating a new list")
return []
def function(arg=make_default()):
arg.append(1)
return arg
Now call:
function()
function()
function()
and see if you can work out what is happening.
Hint: how many new lists are created? when are they created?
--
Steven
More information about the Tutor
mailing list