为什么我们必须这样做:
global x
x = "Hello World!"
当这更具可读性时:
global x = "Hello World"
这是为什么,有什么原因吗?
最佳答案
Python 的目标是尽可能的可读。为了达到这个目标,必须强制用户以明确定义的方式行动——例如您必须正好使用四个空格。就像这样,它定义了 global
关键字是一个简单的语句。这意味着:
A simple statement is comprised within a single logical line. Simple Statements
和
Programmer’s note: the global is a directive to the parser. It applies only to code parsed at the same time as the global statement. The global statement
如果你这样写:
global x = 5
你会有两个逻辑操作:
- 口译员请使用全局 x 而不是本地 x
- 将 5 赋值给 x
在一行中。此外,global
似乎仅适用于当前行,而不适用于整个代码块。
TL;TR
这是为了迫使用户编写可读性更好的代码,这些代码被拆分为单个逻辑操作。
关于python - 为什么变量在赋值之前必须声明为全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37690361/