>> x = [] >>> x. insert(0, 'hi'-6ren">
gpt4 book ai didi

python - 为什么python在 "."之后允许对象和方法名之间有空格

转载 作者:行者123 更新时间:2023-11-28 19:00:36 31 4
gpt4 key购买 nike

有谁知道为什么 python 允许您在对象和称为“.”的方法名称之间放置无限量的空格? ?

这里有一些例子:

 >>> x = []
>>> x. insert(0, 'hi')
>>> print x
['hi']

另一个例子:

>>> d = {}
>>> d ['hi'] = 'there'
>>> print d
{'hi': 'there'}

类也是一样。

>>> myClass = type('hi', (), {'there': 'hello'})
>>> myClass. there
'hello'

我正在使用 python 2.7我尝试进行一些谷歌搜索并查看 python 源代码,但我找不到允许这样做的任何理由。

最佳答案

. 就像一个运算符。你可以做 obj 。 attr 与您可以执行 this + thatthis * that 或类似操作的方式相同。 language reference说:

Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens.

因为这条规则太笼统了,我假设执行它的代码在解析过程的早期。它不是特定于 . 的。它只是忽略除行首或字符串内部之外的所有空格。

关于python - 为什么python在 "."之后允许对象和方法名之间有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52996409/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com