Lists in classes

Wildemar Wildenburger wildemar at freakmail.de
Thu Jul 12 17:51:58 CEST 2007


Bart Ogryczak wrote:
> On 12 jul, 17:23, Jeremy  Lynch <jeremy.ly... at gmail.com> wrote:
>   
>> Hello,
>>
>> Learning python from a c++ background. Very confused about this:
>>
>> ============
>> class jeremy:
>>         list=[]
>>     
>
> You've defined list (very bad choice of a name, BTW), as a class
> variable. To declare is as instance variable you have to prepend it
> with "self."
>
>   
Ouch!

'self' is *not* a reserved ord in python, it doesn't do anything. So 
just popping 'self' in front of something doesn't bind it to an instance.
Here is how it works:

class Jeremy(object):  # you better inherit from 'object' at all times
    classlist = []  # class variable
    def __init__(self):  # "constructor"
        self.instancelist = []  # instance variable
    def add_item(self, item):
        self.instancelist.append(item)

'self' is the customary name for the first argument of any instance 
method, which is always implicitly passed when you call it. I think it 
translates to C++'s 'this' keyword, but I may be wrong. Simply put: The 
first argument in an instance-method definition (be it called 'self' or 
otherwise) refers to the current instance.
Note however that you don't explicitly pass the instance to the method, 
that is done automatically:

j = Jeremy()  # Jeremy.__init__ is called at this moment, btw
j.add_item("hi") # See? 'item' is the first arg you actually pass

I found this a bit confusing at first, too, but it's actually very 
clean, I think.
/W



More information about the Python-list mailing list