Lists in classes

Jason Drew jasondrew72 at
Thu Jul 12 19:22:36 CEST 2007

Thanks for clearing up the other incorrect answers! In true Python
fashion, I would also remind everyone of the *documentation* - in
particular the Python tutorial. These are very elementary mistakes to
be making - even worse as part of attempted answers.

The Python tutorial is at

In particular see the section on classes:

Note however that the tutorial doesn't show the current best practice
of subclassing your classes from "object", i.e.
class MyClass(object):


On Jul 12, 11:51 am, Wildemar Wildenburger <wilde... at>
> Bart Ogryczak wrote:
> > On 12 jul, 17:23, Jeremy  Lynch < at> 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