friends , If you need to reprint, please indicate the source :https://blog.csdn.net/jiangjunshow
Statement : During the teaching of artificial intelligence technology , Many students mentioned to me python Related issues , So in order to let the students master more extended knowledge and better understand AI technology , I put the assistant in charge of sharing this python Series of tutorials , I hope that helps ! Because of this python The tutorial wasn't written by me , So it's not as good as mine AI Technology teaching is humorous , It's boring to learn ; But its knowledge is in place , It's also worth reading ! Want to learn AI Technical students can click to jump to my Teaching website .PS: If you don't understand this article, please read the previous article first , Step by step, learn a little everyday, and you won't find it difficult !
global The sentence is Python The only statement in that looks something like a declaration statement . however , It is not a declaration of type or size , It is a namespace declaration . It tells Python The function is intended to generate one or more global variable names . in other words , Exists within the scope of the entire module ( Namespace ) Variable name :
X = 88 # Global X
def func():
global X
X = 99 # Global X: outside def
func()
print(X) # Prints 99
In this example, we added a global Statement , In order to be in def Within X Can be referenced in def In addition to the X.
Let's take another example
y,z = 1,2 # Global variables in module
def all_global():
global x # Declare globals assigned
x = y + z # No need to declare y,z: LEGB rule
here ,x、y and z All are all_global Global variables in functions .y and z Global variable , Because they are not assigned in a function ;x Global variable , Because it passes through global Statement explicitly maps itself to the scope of the module . If not used global In words ,x Will be considered a local variable due to the assignment .
y and z It didn't go on global Statement .Python Of LEGB The lookup rule will automatically find them from the module . Besides , Be careful x It may not exist before the function runs . If so , The assignment statement in the function will be automatically created in the module x This variable .