Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to use class refernce in another file

Tags:

python

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?

like image 856
sarbjit Avatar asked Dec 01 '25 14:12

sarbjit


2 Answers

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"
like image 130
zenpoy Avatar answered Dec 03 '25 06:12

zenpoy


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"]
like image 31
nmclean Avatar answered Dec 03 '25 05:12

nmclean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!