为什么python允许在“."之后的对象和方法名称之间有空格? [英] Why does python allow spaces between an object and the method name after the "."

查看:50
本文介绍了为什么python允许在“."之后的对象和方法名称之间有空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

以下是一些示例:

 >>>x = []>>>X.插入(0,'嗨')>>>打印 x['你好']

另一个例子:

<预><代码>>>>d = {}>>>d ['hi'] = '那里'>>>打印{'你好呀'}

对于类也是一样的.

<预><代码>>>>myClass = type('hi', (), {'there': 'hello'})>>>我的课.那里'你好'

我使用的是 python 2.7我尝试进行一些谷歌搜索并查看 python 源代码,但我找不到任何允许这样做的原因.

解决方案

. 就像一个运算符.你可以做 obj .attr 与您可以执行 this + thatthis * that 或类似的方式相同.语言参考 说:

<块引用>

除了在逻辑行的开头或字符串文字中,空格、制表符和换页符可以互换使用以分隔标记.

因为这个规则太笼统了,我假设执行它的代码在解析过程的早期.它与 . 无关.它只是忽略除行首或字符串内部之外的所有空白.

Does anyone know why python allows you to put an unlimited amount of spaces between an object and the name of the method being called the "." ?

Here are some examples:

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

Another example:

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

It is the same for classes as well.

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

I am using python 2.7 I tried doing some google searches and looking at the python source code, but I cannot find any reason why this is allowed.

解决方案

The . acts like an operator. You can do obj . attr the same way you can do this + that or this * that or the like. The language reference says:

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.

Because this rule is so general, I would assume the code that does it is very early in the parsing process. It's nothing specific to .. It just ignores all whitespace everywhere except at the beginning of the line or inside a string.

这篇关于为什么python允许在“."之后的对象和方法名称之间有空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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