程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python series tutorial 183 - Global statements

編輯:Python

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved