Created
May 19, 2013 19:49
-
-
Save numberoverzero/5608748 to your computer and use it in GitHub Desktop.
factory that captures the usual args, kwargs of instantiation and saves them so multiple copies can be created.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
class Factory(object): | |
def __init__(self, cls, *args, **kwargs): | |
self._cls = cls | |
self._args = args | |
self._kwargs = kwargs | |
@property | |
def instance(self): | |
return self._cls(*(self._args), **(self._kwargs)) | |
def f(cls): | |
@wraps(cls) | |
def init(*args, **kwargs): | |
return Factory(cls, *args, **kwargs) | |
return init | |
#================================ | |
# | |
# USAGE | |
# | |
#================================ | |
class Foo(object): | |
"Foo object thing" | |
def __init__(self, a, b, c="c"): | |
print("Created foo") | |
self.a = a | |
self.b = b | |
self.c = c | |
def print_foo(self): | |
print(self.a, self.b, self.c) | |
factory = f(Foo)("alpha", "bravo", "charlie") | |
instance1 = factory.instance | |
instance2 = factory.instance | |
instance2.b = "balloon" | |
instance1.print_foo() | |
instance2.print_foo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment