Python 跨模块使用全局变量(自定义类型)

gol.py

def _init():#初始化
    global _global_dict
    _global_dict = {}

def set_value(key,value):
    """ 定义一个全局变量 """
    _global_dict[key] = value

def get_value(key,defValue=None):
    """ 获得一个全局变量,不存在则返回默认值 """
    try:
        return _global_dict[key]
    except KeyError:
        return defValue

t1.py

class A():
    def show(self):
        print("I'am a")

t2.py

import gol

a = gol.get_value('a')
a.show()

t3.py

import t1
import gol

gol._init()
a = t1.A()
gol.set_value('a',a)
import t2
#t2.a.show()

文件结构
在这里插入图片描述

posted @ 2021-06-06 22:27  dotJunz  阅读(214)  评论(0编辑  收藏  举报