Re: [Tutor] Question about Classes

Magnus Lycka magnus at thinkware.se
Mon Nov 24 17:24:31 EST 2003


Hi Mike!

Mike wrote:
> In an effort to understand how classes work I have created 2 classes.

One of the first thing you should know about classes is that
inheritance means "is-a". In other words, by letting "Contact"
inherit "Email" as you did in your code, you are claiming that
a Contact is a kind of Email. I don't think you really see the 
world like that. I certainly don't. ;) This kind of misuse of 
class mechanisms will only cause grief.

A contact might *have* emails. That implies composition, or
an aggregate, that is, the person could have an emails attribute.
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()
> 
> 	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()

-- 
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