Help understanding an Object Oriented Program example
Ulrich Eckhardt
ulrich.eckhardt at dominolaser.com
Mon Oct 29 06:21:58 EDT 2012
Am 29.10.2012 00:30, schrieb goldtech:
> class Contact:
> all_contacts = []
> def __init__(self, name, email):
> self.name = name
> self.email = email
> Contact.all_contacts.append(self)
Okay, a class that automatically registers all instances in a central list.
> 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?
Since you don't use "c", there is no use storing it at all! Note that
you don't have to store a reference to an object that you created, just
calling "Contact('fou', 'barre')" without assigning to anything is fine.
Note that I don't find this example good, in reality I would prefer a
factory method (e.g. called "register(name, email)") that makes clear
that you are not simply creating an instance.
Also, concerning OOP, classes in Python are objects, too. Therefore,
this could be decorated with "@classmethod" to allow the use with
derived classes. However, I think that's going a bit too far at the
moment. Just wanted to mention that there are more features waiting for
you to discover.
> 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?
How would an object use a method defined in the class? The point is that
when calling "fou.barre(42)", the expression "fou.barre" is evaluated
first and then used in a call expression with the parameter 42. Note
that you can even evaluate that expression without calling the resulting
function, but instead assign its result to a variable. In order to
evaluate that expression, Python first looks for an attribute "barre" in
the instance and returns that if found. If the instance doesn't have it,
it looks in the class via the instances __class__ attribute. At that
point, a little case-specific magic happens. If it finds a normal
function without "@classmethod" or "@staticmethod" decorator, it returns
this function with the first parameter (customary called "self") bound
to the instance. If it finds a non-function, that object is returned
as-is instead.
To sum up, you can use "Contact.all_contacts" or e.g. "c.all_contacts"
to refer to the list of contacts. The second syntax also includes
"self.all_contacts" when inside a memberfunction, after all the "self"
is nothing magic or special.
Uli
More information about the Python-list
mailing list