[Tutor] Storing information as attributes or in a dictionary

Michiel de Hoon mjldehoon at yahoo.com
Tue Sep 18 16:14:26 CEST 2012


Dear all,

Suppose I have a parser that parses information stored in e.g. an XML file. I would like to design a Python class to store the information contained in this XML file.

One option is to create a class like this:

class Record(object):
    pass

and store the information in the XML file as attributes of objects of this class, as in

>>> handle = open("myxmlfile.xml")
>>> record = parse(handle) # returns a Record object
>>> record.name
"John Doe"
>>> record.birthday
"February 1, 1920"

Alternatively I could subclass the dictionary class:

class Record(dict):
    pass

and have something like

>>> handle = open("myxmlfile.xml")
>>> record = parse(handle) # returns a Record object
>>> record['name']
"John Doe"
>>> record['birthday']
"February 1, 1920"

I can see some advantage to using a dictionary, because it allows me to use the same strings as keys in the dictionary as in used in the XML file itself. But are there some general guidelines for when to use a dictionary-like class, and when to use attributes to store information? In particular, are there any situations where there is some advantage in using attributes?

Thanks,
-Michiel.


More information about the Tutor mailing list