Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #7441
| Date | 2011-06-11 05:06 -0500 |
|---|---|
| From | Andrew Berg <bahamutzero8825@gmail.com> |
| Subject | Re: Square bracket and dot notations? |
| References | <4ab9f6bd-cf2d-4c0a-8eda-7d8ffa6bd6c4@v10g2000yqn.googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.127.1307786802.11593.python-list@python.org> (permalink) |
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.
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Square bracket and dot notations? Asen Bozhilov <asen.bozhilov@gmail.com> - 2011-06-11 02:41 -0700
Re: Square bracket and dot notations? Andrew Berg <bahamutzero8825@gmail.com> - 2011-06-11 05:06 -0500
Re: Square bracket and dot notations? Ben Finney <ben+python@benfinney.id.au> - 2011-06-11 20:11 +1000
Re: Square bracket and dot notations? Francesco Bochicchio <bieffe62@gmail.com> - 2011-06-11 03:46 -0700
Re: Square bracket and dot notations? Asen Bozhilov <asen.bozhilov@gmail.com> - 2011-06-11 07:40 -0700
Re: Square bracket and dot notations? Terry Reedy <tjreedy@udel.edu> - 2011-06-11 15:49 -0400
Re: Square bracket and dot notations? Asen Bozhilov <asen.bozhilov@gmail.com> - 2011-06-11 13:41 -0700
csiph-web