Lists in classes

Jason Drew jasondrew72 at gmail.com
Thu Jul 12 13:22:36 EDT 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 http://docs.python.org/tut/tut.html

In particular see the section on classes: http://docs.python.org/tut/node11.html

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

-Jason

On Jul 12, 11:51 am, Wildemar Wildenburger <wilde... at freakmail.de>
wrote:
> 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