I have 2 classes and I count different stuff with them. I would like to use the same collections.Counter object for the two classes, because some of the things I count are in common. What is the most pythonic way to do this?
So far I have 2 different classes using 2 separate counters:
from collections import Counter
class Shapes():
def __init__():
self.c = Counter(rotate=0, translate=0, operation=0)
class Tools():
def __init__:
self.c = Counter(hammer=0, scissor=0, operation=0)
One option would be to move the counter outside all classes, but it doesn't look so nice because it's not needed to have it global, I want to share it only between two classes.
from collections import Counter
c = Counter(rotate=0, translate=0, hammer=0)
class Shape():
pass
class Tool():
pass
What I would like to do is something like this, with just one counter for both classes:
A = Operations()
B = Tools()
# Counter['operation'] = 0 at this point
A.do_operation() # Do something and increase c['operation'] by one
B.do_operation() # Do something and increase c['operation'] by one
# Now Counter['operation'] = 2
You could have a class that maintains a Counter then subclass that as follows:
Output:
You could also use a singleton pattern like this: