classes vs dicts

Peter Otten __peter__ at web.de
Thu May 6 10:46:52 EDT 2004


Yermat wrote:

> So the real question is what do you prefer to type : somePerson.name or
> somePerson["name"] ?

And if you [OP] really cannot make up your mind:

>>> class Both:
...     def __getitem__(self, key):
...             return self.__dict__[key]
...     def __setitem__(self, key, value):
...             self.__dict__[key] = value
...
>>> b = Both()
>>> b["name"] = "won't tell"
>>> b.name
"won't tell"
>>> b.address = "in the middle of nowhere"
>>> b["address"]
'in the middle of nowhere'
>>> b["this is nasty"] = "now what?"
>>>

After all a class is just syntactic sugar for a dictionary and a dictionary
is just a class, which is...

:-)
Peter




More information about the Python-list mailing list