I need to make sure that both files have the same Car class object. How do I do this?
main.py
import newFile1
class Car:
def __init__(self, speed):
self.speed = speed
car = Car(10)
print("main.py:", id(car))
newFile1.py
from main import car
print("newFile1.py:", id(car))
Output:
main.py: 2095179490752
newFile1.py: 2095179490752
main.py: 2095175287280
The IDs are different, how do I make them the same?
What I think is happening is that you when you run python main.py
, python executes main.py
as a script rather than importing it as a module. When it executes the first line of main.py
, python imports newFile1.py
which then imports main.py
as a module, causing it to be executed a second time. During that section execution, the interpreter finally gets to the lines that create the Car
class and the car
instance. It then prints the id of the car
instance. That instance is then imported into newFile1.py
(or technically, it is added to newFile1
's namespace), and then its id is printed again. Then execution returns to the main.py
script that you ran from the command line. A new class called Car
is created and an instance of that class called car
is instantiated. That new instance's id is, of course, different from the different instance of a different class that was printed in the main
module and the newFile1
module.
If you created a different python file as a script, say realmain.py
, and imported main
into that, you would have only one instance of the Car class and you could then share the car
instance created there. But as has been pointed out in the comments, your modules have a circular reference, so you won’t actually be able to import the main
module from a separate script.
And as has also been pointed out, you can solve the circular reference quite easily because you don't actually use newFile1
in main
, so you can just delete that import. That would give you something like:
main.py
class Car:
def __init__(self, speed):
self.speed = speed
car = Car(10)
print("main.py:", id(car))
newFile1.py
from main import car
print("newFile1.py:", id(car))
realmain.py
from main import car
import newFile1
print("realmain.py:", id(car))
Then when you run python realmain.py
you'll get output like
main.py: 4315218384
newFile1.py: 4315218384
realmain.py: 4315218384