在Python中,模块间传递对象的最佳方式是什么?

1 投票
1 回答
2794 浏览
提问于 2025-04-17 22:51

我需要从一个模块访问另一个模块里的一个对象:

module_1.py:

import module_2

class A():
    def __init__():
         do_sth()

class B():
    def __init__():
         do_sth()
         self.x = some_object()
         do_sth_else(x)

    def show():
        show_gui()

def start():
    y = B()
    y.show()

if __name__ == "__main__":
    start()

module_2.py:

def run_it(arg):
    run_run_run()

我需要从 module_1 里获取 self.x 这个对象,这样我才能把它作为参数传给 module_2 里的 run_it() 函数。需要注意的是,module_1 也导入了 module_2

有没有什么常用的方法可以用来访问其他模块里的对象呢?

1 个回答

0

现在根据你的修改,看起来你想要的是这样的:

from module_1 import B

run_it(B().x)

这就引出了一个问题:如果 x 对所有 B 的对象都是一样的,为什么不把它设为类的成员,而不是实例的成员呢?可以这样做:

class B:
    x = some_object()

    def __init__(self):
         do_sth()
         do_sth_else(B.x)

    def show(self):
        show_gui()

然后在另一个模块中

run_it(B.x)

关于你的评论:y 是局部变量,只在 start 函数内有效。你需要把它返回:

def start():
    y = B()
    y.show()
    return y

然后

run_it(start())

另外,y.show() 会出错,因为 show 函数不接受参数,而 y 会被当作 self 传进去。

撰写回答