python实现跨文件全局变量的方法

yipeiwu_com6年前Python基础

在使用Python编写的应用的过程中,有时候会遇到多个文件之间传递同一个全局变量的情况。本文就此给出了如下的解决方法供大家参考。

文件1:globalvar.py

#!/usr/bin/env python2.7 
class GlobalVar: 
  db_handle = None 
  mq_client = None 
def set_db_handle(db): 
  GlobalVar.db_handle = db 
def get_db_handle(): 
  return GlobalVar.db_handle 
def set_mq_client(mq_cli): 
  GlobalVar.mq_client = mq_cli 
def get_mq_client(): 
  return GlobalVar.mq_client 

文件2:set.py

import globalvar as GlobalVar 
def set(): 
  GlobalVar.set_mq_client(10) 
  print "------set mq_client in set.py------mq_client: " + str(GlobalVar.get_mq_client()) 

文件3:get.py

#!/usr/bin/env python2.7 
import globalvar as GlobalVar 
def get(): 
  print "------get mq_client in get.py------mq_client: " + str(GlobalVar.get_mq_client()) 

文件4:main.py

#!/usr/bin/env python2.7 
import set 
import get 
set.set() 
get.get() 

其中globalvar.py中定义了两个全局变量,在set.py中的set函数中对其进行赋值,在get.py文件中的get函数取值并打印。main.py函数作为应用入口,调用set和get。

这样就可以看到一个完整的应用中,全局变量的跨文件使用。

相关文章

Python中的引用和拷贝浅析

If an object's value can be modified, the object is said to be mutable. If the value cannot b...

利用setuptools打包python程序的方法步骤

利用setuptools打包python程序的方法步骤

一、准备工程文件 1.创建工程leeoo 2.在工程根目录下创建setup.py文件 3.在工程根目录下创建同名package 二、编辑setup.py 1.编辑setup.py文...

python中将字典转换成其json字符串

#这是Python中的一个字典 dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': {...

对python中字典keys,values,items的使用详解

在python中对字典进行遍历时,可以直接使用如下模式: dict = {"name": "jack", "age": 15, "height": 1.75} for k...

Python关于excel和shp的使用在matplotlib

Python关于excel和shp的使用在matplotlib

关于excel和shp的使用在matplotlib 使用pandas 对excel进行简单操作 使用cartopy 读取shpfile 展示到matplotlib中 利用s...