Home > Enterprise >  Code refactoring, where to instantiate an object
Code refactoring, where to instantiate an object

Time:11-06

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?

CodePudding user response:

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
.
.
.
  • Related