You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何跨多文件访问同一类并实现运行时数据读写共享?

跨模块读写类实例变量的实现方案

原代码的问题

  • file1里的global Internal完全多余,模块级定义的类本身就是全局可访问的,没必要加这个声明
  • file2里的myobject没定义,也没正确引用file1的Internal类,更没把实例放到其他模块能访问的地方
  • file3里直接用Internal却没从file1导入,还想直接访问类的属性,但我们要的是实例的属性

修改后的代码

file1.py

定义类,同时加一个模块级变量用来存实例,方便其他模块读写

# file1.py
class Internal:
    def __init__(self, do_stuff=None):
        self.do_stuff = do_stuff

# 模块级变量,专门用来存储Internal的实例
internal_instance = None

file2.py

导入file1,创建实例并赋值到file1的模块变量里

# file2.py
import file1
import file3

# 创建实例并挂载到file1的模块级变量上
file1.internal_instance = file1.Internal(do_stuff="foo")

file3.py

从file1导入模块,直接访问已初始化的实例属性

# file3.py
import file1

# 读取实例的do_stuff属性
print(file1.internal_instance.do_stuff)
# 输出结果: foo

运行注意事项

得先跑file2.py完成实例的初始化,再运行file3.py才能读到正确的值。如果是在同一个项目里调用,要保证初始化逻辑(就是file2里的代码)先执行,再执行读取的逻辑。

扩展用法

要是想随时修改变量,在任意模块里直接改就行:

import file1
file1.internal_instance.do_stuff = "bar"

之后其他模块再读这个属性,拿到的就是更新后的"bar"了。

内容的提问来源于stack exchange,提问作者BenitzCoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:45:42