Cool object trick

Fredrik Lundh fredrik at pythonware.com
Fri Dec 17 09:40:24 EST 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 
> overboard.

unless you're willing to use getattr() for thos oddball cases, of course.

    >>> class Dummy:
    ...     pass
    ...
    >>> x = Dummy()
    >>> setattr(x, "spam&egg", "hello")
    >>> getattr(x, "spam&egg")
    'hello'
    >>> 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)

</F> 






More information about the Python-list mailing list