Square bracket and dot notations?

Andrew Berg bahamutzero8825 at gmail.com
Sat Jun 11 06:06:27 EDT 2011


On 2011.06.11 04:41 AM, Asen Bozhilov wrote:
> Hi all,
> I am beginner in Python. What is interesting for me is that Python
> interpreter treats in different way dot and square bracket notations.
> I am coming from JavaScript where both notations lead prototype chain
> lookup.
>
> In Python it seems square bracket and dot notations lead lookup in
> different "store".
>
> Simple example with dict object:
>
> d = {"key" : "value"}
>
> print d["key"] #value
>
> print d.key #AttributeError
d is this case is a dictionary object, and therefore has keys you can
look up (with square brackets). The same is true with lists and tuples
(which have integers as "keys"). An arbitrary object can have arbitrary
values in arbitrary variables in its namespace (accessed with dots).
Objects can have a __dict__ variable that stores the variables in their
namespace as a dictionary (not entirely sure how this works; I'm sure
someone can expand on it).

With:
class simpleObject():
    pass
a = simpleObject()

This:
a.key = 'value'
a.otherkey = 'othervalue'

I simpler than:
a.props = {}
a.props['key'] = 'value'
a.props['otherkey'] = 'othervalue'


However, if you want your object to hold several different sets of keys
and respective values, dictionaries (or lists/tuples) make more sense.



More information about the Python-list mailing list