Hi,
Can somebody please explain to me why:
class SomeClass:
def __init__(self, contents=[]):
self.contents = contents[:]
def add(self, element):
self.contents.append(element)
when called a second time (i.e. to create a new instance of a SomeClass
object) results in self.contents being assigned an empty list when say for
example I've done:
foo = SomeClass()
foo.add(1)
foo.add(2)
beforehand?
I understand that the default value is only evaluated once and therefore
retains a reference to the same list which is why:
self.contents = contents
results in objects sharing the same contents, but I was under the
impression that [:] basically produced a copy of an entire list. So
in that case wouldn't blah.contents contain a copy of foo.contents when
it's created given that no other list is specified as a parameter to
__init__?
I've read a couple of explanations which were rather vague so I'm having
trouble grokking what's going on.
Thanks.