简体   繁体   中英

Python: How can I initialise object in one module and use it in another

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

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

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

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__() .

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

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM