Skip to content

Instantly share code, notes, and snippets.

@oyakata
Created August 12, 2011 14:45
Show Gist options
  • Save oyakata/1142186 to your computer and use it in GitHub Desktop.
Save oyakata/1142186 to your computer and use it in GitHub Desktop.
クラスを使わずカウンターを作ってみる
# -*- coding:utf-8 -*-
from collections import defaultdict
from functools import partial
def counter(*keys):
"""クラスを使わずにカウンターを作る。
>>> cnt = counter("foo", "bar", "baz")
>>> cnt.foo()
>>> cnt.foo()
>>> cnt.bar()
>>> cnt.bar()
>>> cnt.bar()
>>> cnt("baz", 7)
>>> cnt.baz()
>>> cnt.all()["foo"]
2
>>> cnt.all()["bar"]
3
>>> cnt.all()["baz"]
8
>>> cnt.reset("foo")
>>> cnt.value("foo")
0
>>> cnt.value("bar")
3
>>> cnt.resetall()
>>> cnt.value("bar")
0
>>> cnt2 = counter("foo", "bar", "baz")
>>> cnt2.foo()
>>> cnt2.value("foo")
1
>>> cnt.value("foo")
0
"""
nums = defaultdict(int)
def count(k, num=None):
if num is None:
nums[k] += 1
else:
nums[k] = num
count.all = lambda: dict(nums)
count.value = lambda k: nums[k]
count.reset = lambda k: count(k, 0)
count.resetall = lambda: nums.clear()
for key in (x for x in keys if not hasattr(count, x)):
# ここでpartialを使わずlambdaを使うとはまる。
setattr(count, key, partial(count, k=key))
return count
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment