[portland] Seeking opinions on choosing data types: dictionary or instance attributes?
mccredie at gmail.com
Tue Nov 27 22:39:09 CET 2007
On Nov 27, 2007 12:23 PM, <ray at bme.ogi.edu> wrote:
> I'm new to python and the Portland users group and all. Correct me if
> I'm offtopic or out of line or anything...
> I'm wondering if you experienced coders have any advice on choosing
> data types in Python. We're writing a program with a large data
> structure and I'm wondering when we should use instance attributes vs.
> when we should use dictionaries. (We'll have some lists when sequence
> matters) My friend loves dictionaries and says to make every class
> a dictionary; then instead of any instance attributes, have key value pairs.
> To me, struct['substruct']['mywidget']['color'] seems more awkward than
> struct.substruct.mywidget.color but he points out that with
> dictionaries it's easier to implement code where you ask the user,
> "What do you want to know about your widget?" and then return
> struct['substruct']['mywidget']['userRequest']. I don't know yet
> if we'll ask any such questions. If the class "Widget" only has two
> attributes, 'color' and 'make' I'm inclined to make them instance
> attributes. But I really don't know...
> Any advice or guidelines? Are there any disadvantages to using all
> these dictionaries?
> Thank you,
Use classes, that is what they are for. It should be mentioned that
dicts are cool, which is why all namespaces in Python are implemented
as dicts. That includes class attributes.
>>> class C(object):
... def __init__(self, a, b, c):
... self.a = a
... self.b = b
... self.c = c
>>> c = C(1,2,3)
>>> d = C('a','b','c')
>>> e = C(0.1, 0.2, 0.3)
>>> f = C(c,d,e)
Hopefully the above demonstrates how trivial it is to get an attribute
when given the name of the attribute as a string.
More information about the Portland