Created
March 27, 2023 00:32
-
-
Save FuruNov/49e1e58b3ab800d56c2b40ce6d6f3fc7 to your computer and use it in GitHub Desktop.
定数を管理する Python クラス
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
| class ConstantSpace: | |
| def __init__(self, **kwargs): | |
| # ユーザーが指定した値を格納する辞書 | |
| self._data = kwargs | |
| def __setattr__(self, name, value): | |
| # 既存の属性を変更しようとした場合はエラーを発生させる | |
| if name in self._data: | |
| raise AttributeError(f"'ConstantSpace' object attribute '{name}' is read-only") | |
| # 新しい属性を追加しようとした場合はエラーを発生させる | |
| if hasattr(self, name): | |
| raise AttributeError(f"'ConstantSpace' object has no attribute '{name}'") | |
| # それ以外の場合は、通常の属性セットメソッドを呼び出す | |
| super().__setattr__(name, value) | |
| def __getattr__(self, name): | |
| # 定数が存在しない場合はエラーを発生させる | |
| if name not in self._data: | |
| raise AttributeError(f"'ConstantSpace' object has no attribute '{name}'") | |
| return self._data[name] | |
| def __dir__(self): | |
| # 定数の名前のリストを返す | |
| return list(self._data.keys()) | |
| """ | |
| >>> cs = ConstantSpace(x=2, y={'name': 'y', 'value': 2}) | |
| >>> print(cs.x) | |
| 2 | |
| >>> print(cs.y) | |
| {'name': 'y', 'value': 2} | |
| >>> cs.y['name'] = 'yprime' | |
| >>> print(cs.y) | |
| {'name': 'yprime', 'value': 2} | |
| >>> print(cs.z) | |
| AttributeError: 'ConstantSpace' object has no attribute 'z' | |
| >>> print(dir(cs)) | |
| ['x', 'y'] | |
| """ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment