Cool object trick
fredrik at pythonware.com
Fri Dec 17 15:40:24 CET 2004
Steve Holden wrote:
>> Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon,
>> obj.sausages, "and", obj.spam' a lot easier ;-)
> Of course this whole thing of substituting attribute access for dictionary keys only works as long
> as the keys are strings with the same syntax as Python identifiers, so one shouldn't go completely
unless you're willing to use getattr() for thos oddball cases, of course.
>>> class Dummy:
>>> x = Dummy()
>>> setattr(x, "spam&egg", "hello")
>>> getattr(x, "spam&egg")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: Dummy instance has no attribute 'spam'
but seriously, turning container elements into attributes should only be done
if it makes sense from a design perspective. (and vice versa; you shouldn't
use a dictionary if an object would make more sense -- but attribute abuse
is a lot more common)
More information about the Python-list