Python method for implementing cross-file global variables _python

Source: Internet
Author: User

In the process of using Python-written applications, you sometimes encounter situations where multiple files pass the same global variable. In this paper, the following solutions are given for your reference.

File 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 

File 2:set.py

Import Globalvar as Globalvar 
def set (): 
  globalvar.set_mq_client (a) 
  print------Set mq_client in set.py------mq_client: "+ str (globalvar.get_mq_client ()) 

File 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 ()) 

File 4:main.py

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

In globalvar.py, two global variables are defined, assigned in the Set function in set.py, and the Get function in the get.py file is evaluated and printed. The main.py function acts as an application portal, invoking set and get.

This allows you to see a complete application in which global variables are used across files.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.