Python中的方括号和点表示法之间有什么区别? [英] What's the difference between the square bracket and dot notations in Python?

查看:170
本文介绍了Python中的方括号和点表示法之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自Javascript背景(可以同时通过.[]表示法访问属性),所以请原谅,但是,两者在Python中到底有什么区别?

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

从我的实验中可以看出,应该始终使用[],不仅可以获取listset的索引,还可以从dictionary中的特定键获取值.这是正确的吗?如果不正确,什么时候在Python中使用.?

From my experimentation it seeems that [] should always be used, both to get the index of a list or set and to get the value from a certain key in a dictionary. Is this correct, and, if not, when do you use a . in Python?

推荐答案

点运算符用于访问任何对象的属性.例如,一个复数

The dot operator is used for accessing attributes of any object. For example, a complex number

>>> c = 3+4j

(除其他外)具有两个属性realimag:

has (among others) the two attributes real and imag:

>>> c.real
3.0
>>> c.imag
4.0

以及其他方法,它都有一个方法conjugate(),它也是一个属性:

As well as those, it has a method, conjugate(), which is also an attribute:

>>> c.conjugate
<built-in method conjugate of complex object at 0x7f4422d73050>
>>> c.conjugate()
(3-4j)

方括号符号用于访问集合的成员,无论是字典还是其他映射,都是通过键访问的:

Square bracket notation is used for accessing members of a collection, whether that's by key in the case of a dictionary or other mapping:

>>> d = {'a': 1, 'b': 2}
>>> d['a']
1

...或序列(如列表或字符串)的索引:

... or by index in the case of a sequence like a list or string:

>>> s = ['x', 'y', 'z']
>>> s[2]
'z'
>>> t = 'Kapow!'
>>> t[3]
'o'

这些集合还分别具有以下属性:

These collections also, separately, have attributes:

>>> d.pop
<built-in method pop of dict object at 0x7f44204068c8>
>>> s.reverse
<built-in method reverse of list object at 0x7f4420454d08>
>>> t.lower
<built-in method lower of str object at 0x7f4422ce2688>

...在上述情况下,这些属性恰好是方法.

... and again, in the above cases, these attributes happen to be methods.

虽然所有对象都有某些属性,但并非所有对象都有成员.例如,如果我们尝试使用方括号表示法来访问我们的复数c的成员:

While all objects have some attributes, not all objects have members. For example, if we try to use square bracket notation to access a member of our complex number c:

>>> c[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'complex' object is not subscriptable

...我们得到一个错误(这是有道理的,因为没有明显的方法让复数具有成员).

... we get an error (which makes sense, since there's no obvious way for a complex number to have members).

使用特殊方法 __getattr__() 分别.解释如何执行此操作超出了此问题的范围,但是您可以在 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆