Skip to content

Instantly share code, notes, and snippets.

@fumieval
Created June 14, 2012 13:34
Show Gist options
  • Save fumieval/2930313 to your computer and use it in GitHub Desktop.
Save fumieval/2930313 to your computer and use it in GitHub Desktop.
__init__と__repr__を書く労力を低減するための混ぜ込みクラス
class once:
def __init__(self, f):
self.f = f
self.memo = {}
def __call__(self, *args):
if args in self.memo:
return self.memo[args]
else:
result = self.f(*args)
self.memo[args] = result
return result
@once
def MultiMix(*params):
"""Example usage:
>>> class Hoge(MultiMix('x', 'y', 'z')):
... def sum(self):
... return self.x + self.y + self.z
... def product(self):
... return self.x * self.y * self.z
>>> hoge = Hoge(1, 2, 4)
>>> hoge
Hoge(1, 2, 4)
>>> hoge.sum()
7
>>> hoge.product()
8
"""
def __init__(self, *args, **kwargs):
arg = iter(args)
for name in params:
try:
value = next(arg)
except StopIteration:
value = kwargs[name]
self.__dict__[name] = value
def __repr__(self):
return self.__class__.__name__ + "(" + ", ".join(I.imap(repr, I.imap(self.__dict__.__getitem__, params))) + ")"
return type("MultiMix({!r})".format(params), (object,), {"__init__": __init__, "__repr__": __repr__})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment