Home  >  Article  >  Backend Development  >  How to declare global variables in python

How to declare global variables in python

silencement
silencementOriginal
2019-06-11 17:23:0712841browse

How to declare global variables in python

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How python manages memoryNext article:How python manages memory