x.abc vs x['abc']
Christian Heimes
lists at cheimes.de
Wed May 13 16:00:23 EDT 2009
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)
HTH
Christian
More information about the Python-list
mailing list