Re: [Tutor] Question about Classes

Magnus Lycka magnus at thinkware.se
Tue Nov 25 09:47:25 EST 2003


> Thanks for "is-a" explanation. My gut told me that this would be some sort of abuse
> of classes but I am new to OO programing and really don't "grok" it yet. 

Seems your instincts are right then.

> So if I wanted to reuse the email functionality in another type of object how would
> I do this? For example if have a contact(person entity) class as well as a
> company(business entity) class.

The only thing I needed to do here was to put "self.emails = Emails()" in
Contact.__init__. It's trivial to put that in Company.__init__ as well.

But you are actually mentioning a well known pattern. It's been analyzed
by Marting Fowler in his book "Analysis Patterns".
 
You have to think about your model in terms of "is a kind of", "has"
and "contains" etc, and design you model based on that. I'll dodge a
bit by saying that this is not really a Python issues... ;)

> > Since the Email class seems to collect emails (plural), it seems
> > it would be better to call is "Emails". If you use it through
> > an "emails" attribute in the Contact, it seems a bit redundant
> > to repeat the word "email" in the method names. (I think this
> > long names just occured because your mistake with inheritance.)
> >
> > class Emails:
> >     def __init__(self):
> >         self._emails=[]
> >
> >     def show(self):
> >          return self._emails
> >
> >     def add(self, email, type):
> >         self._emails.append((type, email))
> >
> >> class Contact(Email):
> >>     def __init__(self
> >>                  ,firstName=''
> >>                  ,lastName=''
> >>                  ):
> >>         """ Initial object """
> >>         self.firstName=firstName
> >>         self.lastName=lastName
> >          self.emails = Emails()

Note the line above!

> >>
> >> 	def updateContact(self
> >> 		,firstName
> >> 		,lastName
> >> 		):
> >> 		""" Save Contact Information """
> >> 		self.firstName=firstName
> >> 		self.lastName=lastName
> >>
> >> 	def showContactInfo(self):
> >> 		return self.firstName + ' ' + self.lastName
> >
> > Now you can do:
> >
> > p.emails.add('x', 'yyy')
> >
> > and
> >
> > p.emails.show()
> 
> You lost me here. In the preceding section you define _email and yet you refer to
> email in this last bit. Does the underscore perform some sort of magic?

No magic at all. I assumed p to be a Contact, just as in your
code. _emails is an attribute in the *Emails* class, containing 
a list. emails is an attribute in the *Contact* class, containg 
an instance of the Emails class.

I use a leading underscore to give a hint that this is an
internal attribute that you shouldn't access directly.

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se



More information about the Tutor mailing list