classes vs dicts

Isaac To kkto at csis.hku.hk
Thu May 6 09:10:29 EDT 2004


>>>>> "Charlie" == Charlie  <charlvj at yahoo.com> writes:

    Charlie> Greetings, I am pretty new to Python and like it very much, but
    Charlie> there is one thing I can't figure out and I couldn't really
    Charlie> find anything in the docs that addresses this.

    Charlie> Say I want to write an address book program, what is the best
    Charlie> way to define a person (and the like): create a class (as I
    Charlie> would do in Java) or use a dictionary?  I guess using
    Charlie> dictionaries is fastest and easiest, but is this recommended?

I read the answers already in the list, which are rather unidirectional: all
advocate for classes.  But I'm unconvinced.  I still believe that there is
no clear-cut winner, and what you should do dopend on how you view the
person.

If you want to associate actions to the person, say associate two persons in
some way; and you want to create various types of persons (subclass it) such
that each of them have different behaviour, then the extra complexity added
by representing the person as a class will definitely pay off.

But, on the other hand, if your application simply treat the person as some
data, turning every access of the person into a getter or a setter or even a
combination will only make code more clumsy and harder to write.

Python is about making the complexity where it worth.  If you cannot see
that a class will help, the safe choice is to do it with a dict.  Later, if
you find that a class would really help, switch to use a class, hopefully by
then you already has a clear idea about why you want a class.  In that way
you won't create a lot of useless class functions at the beginning when the
actual use of the class is unclear.  And you won't waste a lot of time doing
design and later find that your application can be written in a completely
different, more elegant way.

Regards,
Isaac.



More information about the Python-list mailing list