我有两堂课,我用它们来数不同的东西。我想对这两个类使用相同的 collections.Counter 对象,因为我计算的一些东西是共同的。最Pythonic的方法是什么?
到目前为止,我有 2 个不同的类,使用 2 个单独的计数器:
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)
一种选择是将计数器移到所有类之外,但它看起来不太好,因为不需要将其全局化,我只想在两个类之间共享它。
from collections import Counter
c = Counter(rotate=0, translate=0, hammer=0)
class Shape():
pass
class Tool():
pass
我想做的是这样的,两个类只有一个计数器:
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
您可以有一个维护 Counter 的类,然后是子类,如下所示:
from collections import Counter
class BaseCounter:
counter = Counter()
def update(self, value):
self.counter.update(value)
class Shape(BaseCounter):
def __init__(self):
...
class Tool(BaseCounter):
def __init__(self):
...
shape = Shape()
shape.update("abc")
tool = Tool()
tool.update("xyz")
# at this point, referencing either tool or shape would equivalent
for kv in tool.counter.items():
print(*kv)
输出:
a 1
b 1
c 1
x 1
y 1
z 1