Last active
July 6, 2024 23:27
-
-
Save nlile/a8a6ea925b7f4872a4491361adcb0dfd to your computer and use it in GitHub Desktop.
Class with Dynamic Properties and ST
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
| from pydantic import BaseModel | |
| from typing import Any, Dict | |
| class ST(BaseModel): | |
| value: str | |
| class DynamicPropertyClass: | |
| def __init__(self, **kwargs): | |
| for key, value in kwargs.items(): | |
| setattr(self, f"_{key}", ST(value=str(value))) | |
| setattr(self.__class__, key, property( | |
| fget=lambda self, k=key: self._get_property(k), | |
| fset=lambda self, v, k=key: self._set_property(k, v) | |
| )) | |
| def _get_property(self, key: str) -> Any: | |
| st_value = getattr(self, f"_{key}") | |
| original_type = type(self.__original_args__[key]) | |
| return original_type(st_value.value) | |
| def _set_property(self, key: str, value: Any): | |
| setattr(self, f"_{key}", ST(value=str(value))) | |
| @classmethod | |
| def create(cls, **kwargs): | |
| instance = cls(**kwargs) | |
| instance.__original_args__ = kwargs | |
| return instance | |
| # Example usage | |
| if __name__ == "__main__": | |
| obj = DynamicPropertyClass.create(name="John", age=30, height=175.5) | |
| print(obj.name) # Output: John | |
| print(obj.age) # Output: 30 | |
| print(obj.height) # Output: 175.5 | |
| print(type(obj.name)) # Output: <class 'str'> | |
| print(type(obj.age)) # Output: <class 'int'> | |
| print(type(obj.height)) # Output: <class 'float'> | |
| print(type(getattr(obj, "_name"))) # Output: <class '__main__.ST'> | |
| obj.name = "Jane" | |
| print(obj.name) # Output: Jane | |
| """ | |
| John | |
| 30 | |
| 175.5 | |
| <class 'str'> | |
| <class 'int'> | |
| <class 'float'> | |
| <class '__main__.ST'> | |
| Jane | |
| """ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment