0% found this document useful (0 votes)
128 views

Python 2 Lab Solution

The document provides a sample code for implementing an address book using Python classes. It defines a Person class to store contact details of an individual and an AddressBook class to manage a dictionary of Person objects indexed by their last name. The AddressBook class has methods to add new contacts and lookup existing contacts by last name or last name and first name.

Uploaded by

John Edokawabata
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views

Python 2 Lab Solution

The document provides a sample code for implementing an address book using Python classes. It defines a Person class to store contact details of an individual and an AddressBook class to manage a dictionary of Person objects indexed by their last name. The AddressBook class has methods to add new contacts and lookup existing contacts by last name or last name and first name.

Uploaded by

John Edokawabata
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

MIT AITI Python Software Development Lab 05: Python Classes, Solution

The following code is just one solution to the exercises, there are many other possibilities to implement the address book.

# Use the following template: # MIT AITI Indonesia Summer 2013 # File: Python2lab.py # Below are templates for your answers to Lab 5 # INSTRUCTIONS: Write your complete name in student_name and age in student_age # Complete the implementation of functions and classes as described in the handout. # Delete the pass statements below and insert your own code. student_name = 'Markus von Rudno' student_age = 22

class Person: ''' Takes in a persons last name, first name, phone number, and email address(es). ''' def __init__(self, lastName, firstName, phoneNumber, emailAddress): self.lastName = lastName self.firstName = firstName self.phoneNumber = phoneNumber self.emailAddress = emailAddress def __str__(self): s = (self.lastName + ', ' + self.firstName + ' -- Phone Number: ' + self.phoneNumber + ' -- Email Address(es): ' + self.emailAddress) return s class AddressBook: def __init__(self): self.contacts = {} def add_person(self, person): if person.lastName not in self.contacts:

self.contacts[person.lastName] = [person] else: self.contacts[person.lastName] += [person] def lookup_contact(self, lastname, firstname=None): matches = self.contacts[lastname] if firstname is None: for p in matches: print p return else: for p in matches: if p.firstName is firstname: print p return

You might also like