x.abc vs x['abc']

Chris Rebert clp2 at rebertia.com
Wed May 13 16:53:37 EDT 2009


On Wed, May 13, 2009 at 1:00 PM, Christian Heimes <lists at cheimes.de> wrote:
> Gunter Henriksen wrote:
>> but that seems like an arcane way to do something
>> which would ideally be transparent... if there is
>> a function in the standard library, that would be
>> good, even if I have to import it.  I guess there is
>> collections.namedtuple... that would not look much
>> prettier... but the main thing to me is for it to
>> be the same way everybody else does it.  I do not
>> prefer the new object be a dict, but it would be ok.
>
> Most objects have an attribute called '__dict__' that acts as a
> container for the attributes of an object.
>
>>>> class Container(object):
> ...     pass
> ...
>>>> container = Container()
>>>> d = {"hello": "world"}
>>>> container.__dict__.update(d)
>>>> container.hello
> 'world'
>
> You can also implemenet __getattr__() like:
>
>    def __getattr__(self, name):
>        try:
>            return self.data[name]
>        except KeyError:
>            raise AttributeError(name)

See also the `namedtuple` type in the `collections` module:
http://docs.python.org/library/collections.html#collections.namedtuple

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list