python的命名为什么不能以数字开头,Python中的变量名不能以数字开头,或者可以吗?...

本文探讨了如何在Python中通过globals()绕过禁止以数字开头的变量名规则,虽然可行但不推荐。作者解释了这种做法的原因和技术细节,并强调了使用自定义字典而非globals()的重要性,以避免滥用和保持代码清晰。
摘要由CSDN通过智能技术生成

This is somewhat academic, but nevertheless.

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

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

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

1

Likewise for locals().

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

edit:

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 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, 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.

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.

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.

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值