Help understanding an Object Oriented Program example

Chris Rebert clp2 at rebertia.com
Sun Oct 28 20:02:12 EDT 2012


On Sun, Oct 28, 2012 at 4:30 PM, goldtech <leegold at operamail.com> wrote:
> Hi,
>
> Trying to learn Python OOP. An example from a book, may not be
> formated after sending post but:
>
> class Contact:
>     all_contacts = []
>     def __init__(self, name, email):
>         self.name = name
>         self.email = email
>         Contact.all_contacts.append(self)
>
> OK, no I do this:
>
>>>> c = Contact('aaa','bbb')
>>>> c = Contact('ccc','ddd')
>>>> c = Contact('eee','fff')
>>>> for i in Contact.all_contacts:
>         print i.name + '  ' + i.email
>
>
> aaa  bbb
> ccc  ddd
> eee  fff
>>>>
>>>> c.name
> 'eee'
>
> So wouldn't be good to add a check that the var (in this case c) does
> not point to any object before creating an object to keep the list
> correct?

I'm unclear on how the list would become "incorrect" or exactly what
sort of check you're thinking of. Please explain what you mean in
greater detail.
Keep in mind that checking for the "definedness" of variables in
Python is generally considered bad and is often infeasible.

> Also all_contacts is a class variable. I think the author is hinting
> that this would be a good idea for a contact list, But I don't fully
> see the usage of it.

I would think he just wants to demonstrate the use of class variables
as opposed to instance variables. It's probably not a good idea for a
serious contact list implementation. But the general technique to
allow a class to keep track of all its instances can sometimes be
useful (e.g. for caching).

> How would each object use a class variable like
> this? What would be the dot notation?

All of the following would work:
Contact.all_contacts  # as in the example
self.__class__.all_contacts
self.all_contacts  # probably not advisable

Which one you ought to use becomes complicated when you consider the
general case where there may be sub/superclasses, where you may want
to rebind the variable, and where there may be an instance variable of
the same name.
Class variables are generally used quite infrequently compared to
regular instance variables.

Cheers,
Chris



More information about the Python-list mailing list