Welcome to your attention 『Python』 series , Ongoing update
Welcome to your attention 『Python』 series , Ongoing update
I've been learning for so long python, I really didn't think of sharing data in multiple modules at the beginning ·····
Today, a writer has encountered difficulties in this field , Let me also study this thing .
Finally, the idea is as follows :
globalManger.py
, Yes 2 A way Set and get Key value pair .moudle1.py
Set key value pairs in , stay moudle2.py
Get the data contents of key value pairs in .main.py
call moudle1.py
and moudle2.py
, It can be realized in moudle2 Call in moudle1 The data of globalManger.py
# @Time : 2022/6/19 9:09
# @Author : Nanli
# @FileName: globalManger.py
# Initialize an empty key value pair Dictionary
def _init():
global _global_dict
_global_dict = {
}
# Set dictionary contents
def set_value(name, value):
_global_dict[name] = value
# Read the contents of the dictionary
def get_value(name, defValue=None):
try:
return _global_dict[name]
except KeyError:
return defValue
module1.py
# @Time : 2022/6/19 9:05
# @Author : Nanli
# @FileName: module1.py
#moudle1 Set up the data , The back can be in moudle2 Get data in
import sys
import globalManger as gm
gm._init()# Initialize dictionary object , It only needs to be run once , All the following data contents will be placed in the new dictionary
gm.set_value(' Nan Li's age ', 22)# Add a key name to the dictionary ' Nan Li's age ', The key value is 22
gm.set_value(' Gender of Nanli ', " male ")
module2.py
# @Time : 2022/6/19 9:05
# @Author : Nanli
# @FileName: module2.py
#module2 Can get moudle1 Set data
import globalManger as gl
name = gl.get_value(' Nan Li's age ')
score = gl.get_value(' Gender of Nanli ')
print(" Nan Li's age :%s\n Gender of Nanli :%s" % (name, score))
main.py
# @Time : 2022/6/19 9:06
# @Author : Nanli
# @FileName: main.py
import module1
print("moudle1 Data setting is completed ")
import module2
print("moudle2 Finished reading and outputting data ")
Direct operation main.py
If you like , Give me one , Pay attention to ! Continue to share with you the problems encountered in the process of typing code !
Copyright notice :
I found you far away @mzh Original works , Reprint must be marked with the original link
Copyright 2022 mzh
Crated:2022-1-10
Welcome to your attention 『Python』 series , Ongoing update
Welcome to your attention 『Python』 series , Ongoing update
【Python Install a third-party library with a one-line command to permanently increase the speed 】
【 Use PyInstaller pack Python file 】
【 Please look forward to more 】