为什么在Python中调用数字文字的方法时出现语法错误?(Why is it a syntax error to invoke a method on a numeric literal in Pyt

编程入门 行业动态 更新时间:2024-10-24 04:48:21
为什么在Python中调用数字文字的方法时出现语法错误?(Why is it a syntax error to invoke a method on a numeric literal in Python?)

我只能在将数字绑定到名称时调用数字上的方法:

>>> 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() 3

I 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()

更多推荐

本文发布于:2023-04-28 00:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329664.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法错误   文字   数字   方法   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!