Created
March 25, 2024 04:54
-
-
Save Geson-anko/98099bdfc5a2c203e27138b5137fa34b to your computer and use it in GitHub Desktop.
新しいインスタンスを生成可能なクラス。MixInとして使っても良い。
This file contains hidden or 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
import copy | |
from typing import Any, Self | |
class Reconstructable: | |
_init_args: tuple[Any, ...] | |
_init_kwds: dict[str, Any] | |
@classmethod | |
def reconstructable_init(cls, *args: Any, **kwds: Any) -> Self: | |
instance = cls(*copy.deepcopy(args), **copy.deepcopy(kwds)) | |
instance._init_args = args | |
instance._init_kwds = kwds | |
return instance | |
@property | |
def is_reconstructable(self) -> bool: | |
return hasattr(self, "_init_args") and hasattr(self, "_init_kwds") | |
def new(self) -> Self: | |
if self.is_reconstructable: | |
return self.__class__.reconstructable_init(*self._init_args, **self._init_kwds) | |
else: | |
raise RuntimeError( | |
"Can not create new instance! Did you forget to use `reconstructable_init`" | |
"instead of `__init___` when creating a instance?" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment