Object-Oriented Programming

Posted 06 March 2011 - 06:59 PM

I've been trying to learn some more advanced Python concepts, and am getting into object-oriented programming. I think I understand most of what I need to, but I'm having one problem that I can't seem to solve no matter how much I search. The assignment is to "Create your own command-line address-book program using which you can browse, add, modify, delete or search for your contacts such as friends, family and colleagues and their information such as email address and/or phone number. Details must be stored for later retrieval." and the hint is to "Create a class to represent the person's information. Use a dictionary to store person objects with their name as the key. Use the pickle module to store the objects persistently on your hard disk. Use the dictionary built-in methods to add, delete and modify the persons." I can manipulate dictionaries, and use the pickle module. I created a class with the following:

class Person:
'''Represents a person in the addressbook'''
def __init__(self, name, number):
self.name = name
self.number = number
print('{0} added to the addressbook, with the number {1}'\
.format(self.name, self.number))
try:
ab[self.name] = self.number
with open('.ab.data') as f:
pickle.dump(ab, f)
except NameError:
print('Address book not yet created. Creating...')
ab = { self.name : self.number}
with open('.ab.data') as f:
pickle.dump(ab, f)
def __del__(self):
try:
del ab[self.name]
print('{0} was removed from the addressbook'.format(self.name))
with open('.ab.data') as f:
pickle.dump(ab, f)
except NameError:
print('That name is not in the address book')

Don't you have to declare variables to be a member of that class? The problem I seem to be hitting is that I don't understand how to let the user add entries when you have to type variable_name = Person(name, number). If they add another user, it would have to be something like variable_name2 = Person(name, number). I don't know how to get the program to use different variable names. How would you approach this assignment?

Replies To: Object-Oriented Programming

Re: Object-Oriented Programming

Posted 06 March 2011 - 11:16 PM

build a wrapper method that takes in a new username and phone number and then adds it to the dictionary. This way you will create a temp Person class variable to be added to the dictionary. So... in your main method, you would call this method to the effect of if the person types in a new name by saying something like:

add("John Doe", 555-123-4567)

The add func would be inside of the Person class you've already built.

Person shouldn't know if they're in a list or not; they don't have to. Part of OO programming is "need to know." If an object doesn't need to know, it shouldn't. The less an object knows about other objects, the less impact changes to those objects will have to the rest of the program.