我可以在字符串文字上调用 str 方法.但是我不能在整数文字上调用 int 方法:
I can call str methods on string literal. But I cannot call int methods on a integer number literal:
Python 2.7.5+ (default, Sep 19 2013, 13:48:49) >>> 1.bit_length() File "<stdin>", line 1 1.bit_length() ^ SyntaxError: invalid syntax >>> a = 1 >>> a.bit_length() 1 >>> ', '.join(['1', '2']) '1, 2' >>>这是为什么?
推荐答案Python 将 1. 视为浮点数的开头,但无法解析该行的其余部分.改成
Python treats 1. as a beginning of a float number, but fails to parse the rest of the line. Change it to
(1).bit_length()通过用括号括起数字文字,我们确保 python 计算括号内的表达式,即 1 并调用该数字的方法.
by enclosing the number literal with parenthesis, we make sure that python evaluates the expression within the parens, which is 1 and call the method on that number.
Python 像这样定义了浮点文字
Python defines floating point literal like this
floatnumber ::= pointfloat | exponentfloat pointfloat ::= [intpart] fraction | intpart "." exponentfloat ::= (intpart | pointfloat) exponent intpart ::= digit+ fraction ::= "." digit+ exponent ::= ("e" | "E") ["+" | "-"] digit+根据该定义,词法分析器认为 1.bit_length() 将是一个浮点文字,因为 1. 匹配 [intpart] 分数 的开头.但该行的其余部分不匹配.这就是它失败的原因.
As per that definition, the lexical analyzer thinks that 1.bit_length() would be a float literal, since 1. matches the [intpart] fraction's beginning. But the rest of the line doesn't match. That is why it fails.
更多推荐
数字文字的调用方法
发布评论