我只能在将数字绑定到名称时调用数字上的方法:
>>> a = 5 >>> a.bit_length() 3我可以调用字符串文字的方法:
>>> 'Hello World'.lower() 'hello world'但是我不能在数字文字上调用方法:
>>> 5.bit_length()这引发了一个SyntaxError 。 这有实际的原因,还是历史性的?
编辑刚刚找到这个相关的问题 ,显示了解决方法(这里也已经提出过)。 我想这也回答了主要问题 - 通过简单的解决方法,可能没有足够的好处使语法更复杂(并且更难解析)来使这项工作。
I can invoke methods on numbers only when I bind them to a name:
>>> a = 5 >>> a.bit_length() 3I can invoke methods on string literals:
>>> 'Hello World'.lower() 'hello world'But I cannot invoke methods on numeric literals:
>>> 5.bit_length()This raises a SyntaxError. Is there a practical reason for that, or is it historic?
Edit Just found this related question that shows workarounds (that have already been suggested here as well). I guess this also answers the main question - with simple workarounds available, there probably wasn't enough benefit to making the grammar more complex (and harder to parse) to make this work.
最满意答案
根据以下规则解析浮点数, 引用文档 ,
floatnumber ::= pointfloat | exponentfloat pointfloat ::= [intpart] fraction | intpart "." exponentfloat ::= (intpart | pointfloat) exponent intpart ::= digit+ fraction ::= "." digit+ exponent ::= ("e" | "E") ["+" | "-"] digit+当Python看到5. ,它认为语法遵循[intpart] fraction | intpart "." [intpart] fraction | intpart "." 规则。 因此,它拾取下一个字符并发现它与fraction规则不匹配。 这就是抛出语法错误的原因。
你可以绕过那个
5 .bit_length()或者将其括在括号中
(5).bit_length()The floating point numbers are parsed as per the following rules, quoting from the docs,
floatnumber ::= pointfloat | exponentfloat pointfloat ::= [intpart] fraction | intpart "." exponentfloat ::= (intpart | pointfloat) exponent intpart ::= digit+ fraction ::= "." digit+ exponent ::= ("e" | "E") ["+" | "-"] digit+When Python sees 5., it thinks that the grammar follows [intpart] fraction | intpart "." rule. So, it picks up the next character and finds that it doesn't match the fraction rule. That is why the syntax error is thrown.
You can get around that by
5 .bit_length()Or enclosing that in brackets like this
(5).bit_length()更多推荐
发布评论