This is the class definition of a Counter(file name: counter.py) which is to be used in a complex application,
class Counter:
def __init__(self):
self.count = 0
def incr(self):
self.count += 1
def decr(self):
self.count -= 1
It turns out that this Class will be instantiated only twice. The two instances will be used by multiple modules.
- When a file is read, counter 1 will be incremented
- When a HTTP call is made, counter 2 will be incremented
What is the correct way to create 2 instances of the Counter class, so that the state of the two instances can be shared across the application?
Shown below is the solution I came up with,
class Counter:
def __init__(self):
self.count = 0
def incr(self):
self.count += 1
def decr(self):
self.count -= 1
fileCounter = Counter()
httpCounter = Counter()
So from another module, I would do the following,
from counter import fileCounter, httpCounter
def readMoxyConfig():
# Do read the file here
fileCounter.incr()
def callMoxyAPI():
# Make the HTTP rest call here
httpCounter.incr()
Are there any loopholes to this approach? If yes, what is the correct way to achieve the same result?
Note: I am not explicitly interested to know how global variables are shared as in this question. What I want to know is the correct way to instantiate multiple objects from the same class and access the instances from any where in the application.