Python中的变量名不能以数字开头或可以以数字开头吗? [英] Variable names in Python cannot start with a number or can they?

查看:490
本文介绍了Python中的变量名不能以数字开头或可以以数字开头吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管有些学术性,但仍然如此.

This is somewhat academic, but nevertheless.

Python语法禁止以数字开头的变量名称,但是可以这样避免:

Python syntax forbids starting a variable name with a number, but this can be sidestepped like so:

>>> globals()['1a'] = 1
>>> globals()['1a']
1

locals()类似.

这是否意味着Python实际上允许它,并且它不是很明显?

Does that mean that Python actually allows it, and that it's just not very visible?

我的问题不是是否允许;我知道Python正式禁止使用它.问题是,为什么我可以通过直接解决globals()来解决它,如果这违反了某些规则或准则,或者它甚至有充分的理由/应用程序允许这样做.

My question is not whether it is allowed; I am aware that it is formally not allowed in Python. The question is why can I work around it by addressing globals() directly, and if that breaks certain rules or guidelines, or if it maybe even have a good reason/application to allow that.

推荐答案

Python解析器禁止以这种方式命名变量,以便分别解析数字和变量,因为命名变量1e1会造成混乱-是吗数字10.0或变量1e1?

Python parser forbids naming variables that way, for the sake of parsing numbers and variables separately, as naming a variable 1e1 would create a chaos - is it the number 10.0 or the variable 1e1?

"Python,请为我输出1e1!" -为什么是10.0?我在那存储了100个!"

"Python, please output for me 1e1!" - "Why is it 10.0? I stored 100 over there!"

但是实际上,变量的存储方式允许将以数字开头的字符串绑定到值,因为该功能在任何类型的哈希映射中均无害,因此使用此功能技巧"可以实现所需的数字前缀名称变量,而不会损害解析器的可分割性.

But the variables are actually stored in a way that allows binding a string that starts with a number to a value, because that feature is no harm in hashing maps of any kind, and so using this "trick" you can achieve your wanted numeral-prefixed-name variable without hurting the parser severability.

从技术上讲,以这种方式命名变量与python准则不违反,但强烈建议不要这样做,并且通常是不必要的.使用globals来注入变量被称为是非常坏习惯,并且这种情况不应该是未解决的.

I would say that technically, naming variables in that manner is not a violation to python guidelines, but it is highly discouraged, and as a rule unnecessary. Using globals for injecting variables is known as a very bad practice and this case should not be an outstanding.

当然,python可以使用诸如字符串之类的数字括起来,例如*123*,但是我相信发明python的目的是使编程更容易,而不是扩展变量命名空间的限制.

Of course, python could have used an encloser to numerals like strings, say *123*, but I believe the intent of inventing python was to make programming easier, not stretching the limits of variable naming space.

实际上,如果必须使用带数字标题的名称,则最好使用自己的字典,而不要使用globals:

Practically speaking, if you must use number-headed names you better do it with your own dictionary, rather than globals:

>>> number_headed_vars = {'1a': 100}
>>> number_headed_vars['1a']
100

这样,您可以创建自己的变量系统-避免滥用globals().

That way you can create your own variables system - and avoid abusing globals().

这篇关于Python中的变量名不能以数字开头或可以以数字开头吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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