OO question

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Mon Jan 1 00:37:53 EST 2007


On Sun, 31 Dec 2006 19:47:12 -0800, fejkadress wrote:

> I want to make an addressbook and I'm new to OO programming, so I
> wonder if this sounds reasonable.
> 
> I think of making a class Address which contains all data about one
> person, that class can have UserDict as baseclass so I can access data
> like object['name'], etc..

If you are using Python 2.2 or greater, you can inherit from dict:


>>> class Address(dict):
...     pass
...
>>> fred = Address({"address": "123 smith street"})
>>> fred['address']
'123 smith street'


But ask yourself, what benefit do you gain by subclassing dict? Why not
just use a dict?

If this is a learning exercise, then sure, go for it, subclass away! But
if this is meant to be real code, then consider what benefits and costs
using OO will give you, compared to a function-based approach.

(Please don't assume that this is a thinly veiled hint that OO is the
wrong approach. It isn't.)


> Then maybe I can have a class AddressBook which has a list that
> contains all those Address objects.
> Does that sound reasonable?

Again, why create an AddressBook class? Why not just have a list of
Addresses?



> And then the real reason that I posted here is:
> If I want to save all addresses to disk, I can have a method, say,
> save() of AddressBook. But then what? What is a good object oriented
> approach? Should each Address object take care of saving itself to the
> file, with a method like writetofile(filename), or should the class
> AddressBook take care of the saving and ask each object for its data?



Here's one approach, assuming that AddressBook is merely a list of
Addresses and that the Address class knows how to write to an open file
object:

def save(list_of_addresses, filename):
    f = file(filename, "w")
    for address in list_of_addresses:
        address.save(f)
    f.close()

Here's a more pure OO approach to do the same thing:

class AddressBook(object):
    def __init__(self, list_of_addresses):
        self.addresses = list_of_addresses

    def save(self, filename):
        f = file(filename, "w")
        for address in self.addresses:
            address.save(f)
        f.close()

Here's a third approach:

class AddressBook(object):
    def __init__(self, list_of_addresses):
        self.addresses = list_of_addresses
        self.currentfile = None

    def save_one_address(self, data):
        data = do_something_with(data)
        self.currentfile.write(data)

    def save(self, filename):
        self.currentfile = file(filename, "w")
        for address in self.addresses:
            self.save_one_address(address.export())
        self.currentfile.close()
        self.currentfile = None


-- 
Steven.




More information about the Python-list mailing list