Example of implementation of Python across file global variables

  • 2020-06-15 09:38:00
  • OfStack

preface

In C language, since variable 1 must be declared first and used later, we can clearly know whether the variable used is global or local, such as:


int a = 5; 
void test(void) 
{ 
a = 1; //  It is not declared first, so global variables are used a 
} 
void test1(void) 
{ 
int a; 
a = 2; //  Declared earlier, so local variables are used a , changes to which the global variable will not be affected a 
} 
void main(void) 
{ 
printf("before: a = %d\n", a); 
test(); 
printf("after test: a = %d\n", a); 
test1(); 
printf("after test1: a = %d\n", a); 
} 

In python, variables don't need to be declared first; they can be used directly.

Implementation of Python across file global variables

In Python, the global keyword can define one variable as a global variable, but this is limited to calling the global variable in one module (py file). Using global x again in another py file is also inaccessible, because there is not one variable called x in this py module, so it will report undefined.

Using the global keyword as a reference, since it can work in one file, we will define a "global variable management module" for global variables

Global variable management module ES27en.ES28en


#!/usr/bin/python
# -*- coding: utf-8 -*-
def _init():
 global _global_dict
 _global_dict = {}
def set_value(name, value):
 _global_dict[name] = value
def get_value(name, defValue=None):
 try:
  return _global_dict[name]
 except KeyError:
  return defValue

Set the global variable a.py


#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import globalvar as gl
gl._init()
gl.set_value('name', 'cc')
gl.set_value('score', 90)

Gets the global variable b.py


#!/usr/bin/python
# -*- coding: utf-8 -*-
import globalvar as gl
name = gl.get_value('name')
score = gl.get_value('score')
print("%s: %s" % (name, score))

The main program main py


#!/usr/bin/python
# -*- coding: utf-8 -*-
import a
import b

Then run the main program file python main.py, which gives cc: 90

conclusion


Related articles: