What's the difference between the square bracket and dot notations in Python?

后端 未结 4 1876
悲&欢浪女
悲&欢浪女 2020-12-05 09:31

I come from a Javascript background (where properties can be accessed through both . and [] notation), so please forgive me, but what, exactly, is

4条回答
  •  没有蜡笔的小新
    2020-12-05 10:11

    . is used for accessing attributes (including methods). [] is used for accessing what are called "items", which typically are the contents of various kinds of container objects.

    JavaScript does not distinguish these two things, but Python does. You are correct that [] is used for accessing the data in a list or dict. . is used, for instance, for accessing methods like list.append and dict.update. It is also used for accessing other data on other kinds of objects; for instance, compiled regular expression objects have a pattern attribute holding the regex pattern (you would access it with rx.pattern).

    In general, the convention is that [] is used for "open-ended" data storage where you don't know ahead of time how much or what sorts of data the object will hold; . is more commonly used for specific data that the object has "by nature" and which is accessed with a predefined name. For instance, just knowing that something as a list doesn't tell you what's in it (for which you use []), but it does tell you that you can append to it (and to access the append method you use .).

    The other major difference between Python and JavaScript in this regard is that in Python, the behavior of both . and [] can be customized by the object. So obj.foo or obj[foo] may do something special if obj is an object that defines its own behavior for them. There are various custom types that make use of this for their own purposes.

提交回复
热议问题