Global variables are a common type of variable in programming languages. Through global definition, they can be created by an object function or anywhere in the program. They can be used by objects in the program. All objects or functions are referenced, and the definition of global variables facilitates program variable sharing, simplifying the addition and modification of programs.
Python also has global variables, and there are two ways to define global variables:
1. Declaration method
This method is directly in the current To define and declare global variables in the module, use the global declaration method and then reference it!
OLD_URL='http://oldboyedu.com' def bb(): global OLD_URL OLD_URL = OLD_URL +'#m' if __name__=='__main__': bb() print OLD_URL #输出: http://oldboyedu.com#m
2. Module method
This method is to define the global variable in a separate module, and then define it in the global module that needs to be used. Global variable module import
#gl.py 全局变量模块定义 GL_A=‘hello’ GL_B=’world’ #test.py 全局变量引用模块 import gl def hello_world() print gl. GL_A, GL_B 输出helloworld
The above is the detailed content of How to declare global variables in python. For more information, please follow other related articles on the PHP Chinese website!