[英]What is the most appropriate way to pass objects between modules in python?
I have to access an object in a module from another module: 我必须从另一个模块访问模块中的对象:
module_1.py: 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: module_2.py:
def run_it(arg):
run_run_run()
I need self.x
object from module_1
so that I can pass it as an argument to run_it()
function in module_2
. 我需要
self.x
从对象module_1
这样我可以通过它作为参数传递给run_it()
函数module_2
。 Note that module_1
also imports module_2
. 请注意,
module_1
也会导入module_2
。
Is there a conventional method to access objects in other modules? 是否有访问其他模块中对象的常规方法?
Now with your corrections, it looks like you want something like this: 现在,您进行了更正,看起来您想要这样的东西:
from module_1 import B
run_it(B().x)
Which raises a question: If x
is the same for all objects of B
, why not make it a class member instead of an instance member. 这就提出了一个问题:如果
x
对于B
所有对象都是相同的,为什么不使它成为类成员而不是实例成员。 Something like: 就像是:
class B:
x = some_object()
def __init__(self):
do_sth()
do_sth_else(B.x)
def show(self):
show_gui()
And in the other module 在另一个模块中
run_it(B.x)
Addressing your comment: y
is local to start
. 解决您的评论:
y
是本地的start
。 You will need to return it: 您将需要返回它:
def start():
y = B()
y.show()
return y
And then 接着
run_it(start())
Also y.show()
will fail horribly as show
doesn't accept parameters and will get passed y
as self
. 另外
y.show()
会严重失败,因为show
不接受参数,并且将y
作为self
传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.