Code refactoring, where to instantiate an object

Question:

I have two files, i.e order.py and shop.py. And I am instantiating a Network object in both of these files. i.e

order.py

from network import Network
...
network = Network()

shop.py

from network import Network
from order import Order
...
network = Network()
order = Order()

As you can see, I am importing from order.py in shop.py. Now if the Network class looks like the below code. Then it’s called twice. and the message Network object created will be printed twice respectively.

class Network:
    def __init__(self):
        print("Network object created")

How to refactor this code, so that the Network object shouldn’t called twice?
How would you refactor it? Should I make another file and instantiate the Network object there? i.e

config.py

form network import Network
network = Network()

and then import config.py in both order.py and shop.py?

Asked By: Mahan Marwat

||

Answers:

You can import already instantiated object too, no need to instantiate again if it’s going to be shared across modules.

shop.py

form network import Network, network
.
.
.
Answered By: ThePyGuy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.