Help understanding an Object Oriented Program example

goldtech leegold at operamail.com
Sun Oct 28 19:30:23 EDT 2012


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?

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. How would each object use a class variable like
this? What would be the dot notation?

I realize this is a code fragment and is no way implementable code.
Any help appreciated. BTW, it's from "Python3 Object Oriented
Programming..." by D. Philips - very clearly written and enjoying
it...Thanks






More information about the Python-list mailing list