There is more than one way to do it - and for no apparent reason.
Paul Wright
-$P-W$- at verence.demon.co.uk
Mon Feb 18 08:13:01 EST 2002
In article <3C70ECB1.2090709 at mxm.dk>, Max M <maxm at mxm.dk> wrote:
>Basically you can say that JScript uses the dictionary notation for
>getting attributes. As fas I can see this is smarter than the way we do
>it in Python where we have several notations for the same action:
>
>In an object:
>setattr(myObj, 'name', 'max')
>getattr(myObj, 'name')
>
>In a dict:
>myObj['name'] = 'max'
>myObj['name']
...
>Wouldn't it be a good idea to unify the dict and the object so that both
>could be called with attribute and dict notation like in JScript?
Not in the language itself, no. Since Python has established a
conceptual difference between dictionary keys and attributes, to change
that now would break existing code. What I mean is that there are
objects which provide a dictionary interface (using "[]") where the
coder does not want to return the attribute of the same name: the
rfc822.Message class, for example.
If you really want it, there's nothing stopping you doing it for your
own classes:
class Thing:
def __getitem__ (self, key):
return getattr (self, key)
def __setitem__ (self, key, value):
setattr (self, key, value)
probably does what you want. See also
<http://www.python.org/doc/current/ref/sequence-types.html>
I'm not sure I'd recommend it, though, as using getattr and setattr is
the standard way to do it.
--
Paul Wright | http://pobox.com/~pw201 |
More information about the Python-list
mailing list