问题描述
在Python中,everything is an object
.
但是再说一遍,为什么以下代码段不起作用?
But then again, why doesn't the following snippet work?
1.__add__(2)
但是,这确实可行:
n = 1
n.__add__(2)
n
和1
有什么区别?
这不是设计失败吗?例如,它也适用于string
文字.
Isn't it a design failure that it doesn't work?For instance, it does work with string
literals as well.
"one".__add__("two")
为了进行比较,它也可以在其他纯面向对象的语言上很好地工作.
For comparison, it works well on other purely object oriented languages too.
让我们仔细看一下这个编译的c#示例:
Let's take a closer look at this compiling c# example:
Console.WriteLine(100.ToString());
那么,从everything is an object
的角度来看,Python
与C#
有何区别?
Then again, what distinguishes Python
from C#
in the perspective of everything is an object
?
推荐答案
Python的解析器故意非常简单-它强制实施的约束之一是,要弄清楚令牌的含义,它只能看一个令牌右侧(它是 LL(1)解析器).
Python's parser is deliberately very simple - one of the constraints it enforces on itself is that, to figure out what a token means, it can only look one token to the right (it is an LL(1) parser).
因此,它看到[number] [dot],并确定它是浮点文字. '_'
不是浮点文字中的有效字符,因此会出现语法错误.
So, it sees [number][dot], and determines that it is a floating point literal. '_'
isn't a valid character to have in a floating point literal, so it gives a syntax error.
克服此问题的最明显,最常见的方法是将数字放在括号中:
The most obvious and most common way to overcome this is to put the number in parentheses:
(1).__add__(2)
这将迫使它在解析器的限制内将1
解释为整数文字,并将点解释为属性访问权限.
This forces it to interpret the 1
as an integer literal, and the dot as attribute access, within the limitations of the parser.
另一个有趣的解决方法是:
Another interesting workaround is this:
>>> 1 .__add__(2)
3
即,在.
之前添加一个空格.事实证明,Python总是在其中留出空间来存储任何属性:
That is, add a space before the .
. It turns out that Python always allows a space there for any attribute lookup:
>>> range(4) .count(3)
1
我发现这很令人惊讶,但是Python似乎在与+
相似的规则下对待.
,因此将在其周围留出尽可能多的空间.
I found this quite surprising, but it seems that Python treats .
under similar rules to +
, and so will allow as much space as you like around it.
这篇关于为什么1 .__ add __(2)无法解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!