List append

Steve Holden steve at holdenweb.com
Sat Sep 15 23:29:25 EDT 2007


Rob E wrote:
> On Sat, 15 Sep 2007 03:25:27 +0000, mouseit wrote:
> 
>> I'm trying to add an element to a list which is a property of an
>> object, stored in an array. When I append to one element, all of the
>> lists are appended!
>>
>> Example Code:
>>
>> class Test:
>>     array = []
>>
>> myTests = [Test() , Test() , Test()]
>> print len(myTests[1].array)
>> myTests[0].array.append( 5 )
>> print len(myTests[1].array)
>>
>> prints:
>> 0
>> 1
>>
>> This is probably a really easy question (I'm very new to python), so
>> thanks in advance for your help!
> 
> Yes, that's easy:
> 
> class myclass:
>    var1 = []
> 
> means that var1 is associated with the class.  If you want an attribute:
> 
> class myclass:
>     def __init__ (self):
>         self.var1 = []
> 
> is the correct way.
> 
It's easy to get confused, though, because when you try to access an 
instance attribute, if the attribute isn't found in the instance the 
interpreter will then look in the class, and then (if there is one) in 
the class's superclass, and so on.

A further complication arises with methods, since even when the method 
is acquired by inheritance it is bound to the instance.

 >>> class Mine(object):
...   pass
...
 >>> Mine.__init__
<slot wrapper '__init__' of 'object' objects>
 >>> mine = Mine()
 >>> mine.__init__
<method-wrapper '__init__' of Mine object at 0x7ff2c3cc>
 >>>

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline




More information about the Python-list mailing list