On 23/04/19 10:08 PM, Steven D'Aprano wrote:
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?



Hello,

You are right. I didn't think on it, as it feels to me very natural as per the experiences from other language like Ruby, JS. It works differently there.

A similar Ruby code gives different output than Python does.

def make_default()
  print("creating a new list")
  return []
end

def function(arg=make_default())
  arg.push(1)
  return arg
end

# Now call:

p(function())
p(function())
p(function())

And on run:

ruby -v sample.rb
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin16]
creating a new list[1]
creating a new list[1]
creating a new list[1]

But python gives to me:

creating a new list
[1]
[1, 1]
[1, 1, 1]

Python being an interpreted language works so differently than its other 2 siblings Ruby, JS. Surprised.

--
Thanks,

Arup Rakshit

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to