[python] Python uses global variables across files

Using global variables across files

When multiple py files use a global variable at the same time, how to use this global variable across files?

(Focus on "Test Development Automation" Gong Zhonghao, view historical articles, more detailed analysis instructions)

1. Error demonstration

The file1.py code is as follows:

num = 1             # 在file1中定义全局变量num=1
def add_value():
    global num
    num += 100

The file2.py code is as follows:


from file1 import * 

def sub_value():
    global num
    num -= 10

add_value()   # 在file2中执行file1中的add_value函数
sub_value()   # 执行sub_value函数
print(num)    # 打印结果:-9

Many students think that 92 should be printed, that is: 1+100-10 = 91. However, only -9 is actually printed, which means that the add_value executed in file2.py did not change the global variable num.

So, how to make num a real global variable?


2. Model correctly

First, we define a glob.py file separately


def _init():  # 初始化
    global _global_num
    _global_num = [1]        # 定义一个列表存放全局变量的初始值

def add_num(num):            # 为全局变量执行加法
    _global_num[0] += num

def sub_num(num):            # 为全局变量执行减法
    _global_num[0] -= num

def get_all():               # 取出全局变量的值
    return _global_num[0]

Secondly, the file1.py file code is as follows:


import glob

glob._init()           # 必须在file1.py中初始化全局变量

def add_value(num):
    glob.add_num(num)

Finally, the file2.py file code is as follows:

import glob
from file1 import *

def sub_value(num):
    glob.sub_num(num)

add_value(100)
sub_value(10)
print(glob.get_all())    # 运行结果:91

If it is helpful to you, like + follow

(Focus on "Test Development Automation" Gong Zhonghao, view historical articles, more detailed analysis instructions)

Guess you like

Origin blog.csdn.net/weixin_44244190/article/details/129260542