Python:如何在一个模块中初始化对象并在另一个模块中使用它 [英] Python: How can I initialise object in one module and use it in another

查看:116
本文介绍了Python:如何在一个模块中初始化对象并在另一个模块中使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的设置:mod1.py:

my setup: mod1.py:

class cars:
    def __init__(self,x,y,z):
        self.x = x

mod2.py:

import mod1
obj = mod1.cars(x,y,z)

mod3.py

from mod2 import obj

现在,当我在 mod3.py 中导入 obj 时,汽车的 init 方法正在执行.我想要它,因为 obj 已经在 mod2.py 中初始化,mod3 应该得到已经初始化的实例而不是创建新的实例.我怎么能在 python 中做到这一点

Now, what's happening is when I am importing obj in mod3.py init method of cars is getting executed. what I want it as obj is already initialised in mod2.py, mod3 should get already initialised instance and not create new one. How can I do that in python

推荐答案

现在,当我在 mod3.py 中导入 obj 时,汽车的 init 方法正在执行.

Now, what's happening is when I am importing obj in mod3.py init method of cars is getting executed.

当然是这样,这就是你告诉 python 要做的.第一次导入模块时(在给定进程中),将执行顶层的所有语句.你在mod2的顶层创建obj,所以第一次导入mod2时,先导入mod1,然后mod1.调用了cars(...),它调用了mod1.cars.__init__().

Of course it is, that's what you told python to do. The first time a module is imported (in a given process), all the statements at the top level are executed. You create obj at the top-level of mod2, so the first time you import mod2, mod1 is imported, then mod1.cars(...) is called, which calls mod1.cars.__init__().

我想要的 obj 已经在 mod2.py 中初始化,mod3 应该得到已经初始化的实例

what I want it as obj is already initialised in mod2.py, mod3 should get already initialised instance

这正是发生的事情.当然对于当前进程 - 对象不存在于进程之外(并且不在进程之间共享)

That's exactly what happens. For the current process of course - objects don't live outside of a process (and are not shared between processes)

每次导入是指从不同模块中的每次第一次导入

by every import I mean every first import from different modules

只要所有这些导入都发生在同一个进程中,mod2.obj 将只为这个进程创建一次.当然,如果你有不同的进程,每个进程都会有它自己的 obj 实例——正如我所说,对象只在运行时存在,进程之间不共享(希望如此).

As long as all those imports happens in the same process, mod2.obj will be created only once for this process. Of course if you have different processes, each process will have it's own instance of obj - as I said, objects only exist at runtime and are not shared between processes (hopefully).

唯一可以将相同模块导入两次的情况是,如果您的 sys.path 搞砸了,并且允许针对两个不同的模块解析相同的模块名称限定名称并且您有一个使用一个限定名称的导入,另一个使用另一个限定名称 - 但这是一种相当罕见的情况.

The only case where you can have the same module imported twice is if your sys.path is messed up and allow a same module name to be resolved against two different qualified names AND you have one import using one qualified name and the other using the other qualified name - but this is a rather uncommon situation.

这篇关于Python:如何在一个模块中初始化对象并在另一个模块中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆