[Tutor] Storing information as attributes or as a dictionary
Michiel de Hoon
mjldehoon at yahoo.com
Mon Sep 17 07:20:48 CEST 2012
Dear all,
Suppose I have a parser that parses information stored in e.g. an XML file. I would like to store the information contained in this XML file as a Python object.
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 30, 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 30, 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