473,320 Members | 2,117 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

constructor list slice confusion

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.

Jul 21 '05 #1
2 1002
Simon Morgan wrote:
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?


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)

When you want modifiable defaults, you can use a class attribute:
class SomeClass: .... default_contents = []
.... def __init__(self, contents=default_contents):
.... self.contents = contents[:]
.... def add(self, elem): self.contents.append(elem)
.... def addDefault(self, elem): self.default_contents.append(elem)
.... def __repr__(self):
.... return "SomeClass(contents=%s, default_contents=%s)" % (
.... self.contents, self.default_contents)
.... foo = SomeClass()
foo SomeClass(contents=[], default_contents=[]) foo.add(1)
foo.addDefault("x")
foo SomeClass(contents=[1], default_contents=['x'])
bar = SomeClass()
bar SomeClass(contents=['x'], default_contents=['x']) bar.add(2)
bar

SomeClass(contents=['x', 2], default_contents=['x'])

Peter
Jul 21 '05 #2
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.

Jul 21 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Jess Austin | last post by:
hi, I like the way that Python does lists, and I love the way it does iterators. But I've decided I don't like what it does with iterators of lists. Lists are supposed to be mutable sequences,...
19
by: David Abrahams | last post by:
Can anyone explain the logic behind the behavior of list slicing with negative strides? For example: >>> print range(10) I found this result very surprising, and would just like to see the...
8
by: Nickolay Kolev | last post by:
Hi all, I have a list whose length is a multiple of 3. I want to get a list of tuples each of which has 3 consecutive elements from the original list, thus packing the list into smaller...
3
by: Dave Opstad | last post by:
According to the documentation the __setslice__ method has been deprecated since Python 2.0. However, if I'm deriving classes from the builtin list class, I've discovered I can't really ignore...
40
by: Ron Adam | last post by:
After considering several alternatives and trying out a few ideas with a modified list object Bengt Richter posted, (Thank You), I think I've found a way to make slice operation (especially far end...
65
by: Steven Watanabe | last post by:
I know that the standard idioms for clearing a list are: (1) mylist = (2) del mylist I guess I'm not in the "slicing frame of mind", as someone put it, but can someone explain what the...
13
by: Jeroen | last post by:
Hi all, I'm trying to implement a certain class but I have problems regarding the copy ctor. I'll try to explain this as good as possible and show what I tried thusfar. Because it's not about a...
5
by: Mike Kent | last post by:
For Python 2.5 and new-style classes, what special method is called for mylist = seq and for del mylist (given that mylist is a list, and seq is some sequence)? I'm trying to subclass list, and...
12
by: lorlarz | last post by:
In the code sample below, how are arguments a legitimate argument to Array.slice? Function.prototype.bind = function(){ var fn = this, args = Array.prototype.slice.call(arguments), object =...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.