I have a situation where I want to use class instance declared in one file in second file. As a small example, see the below code :
How I am solving it as of now?
File2 (To be executed):
# Prog2:
from prog1 import *
cls1.dict["name"] = "John"
File1
# Prog1:
class Myclass(object):
def __init__(self):
self.dict = {}
cls1 = Myclass()
import prog2
print cls1.dict["name"]
Is there a better way of doing it?
Why the circular dependency?
File 1:
# file 1
class MyClass(object):
def __init__(self):
self.dict = {}
cls1 = MyClass()
cls1.dict["name"] = "John"
File 2:
# file 2
from prog1 import cls1
print cls1.dict["name"]
>> "John"
The primary purpose of import is to make functionality available. It generally shouldn't be used as a method of executing a procedure. Your "prog2" should contain a function with a parameter:
def execute(instance):
instance.dict["name"] = "John"
"prog1" can then call this with the appropriate instance:
import prog2
class Myclass(object):
def __init__(self):
self.dict = {}
cls1 = Myclass()
prog2.execute(cls1)
print cls1.dict["name"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With