|
| 1 | +from typing import Any, ClassVar, Self, Type, TypeVar, overload |
| 2 | + |
| 3 | +from typing_extensions import dataclass_transform |
| 4 | + |
| 5 | + |
| 6 | +class TpptSlideMasterMeta(type): |
| 7 | + """TpptSlideMasterのメタクラス""" |
| 8 | + |
| 9 | + def __getattr__(self, key: str) -> Any: |
| 10 | + if key in self.__annotations__: |
| 11 | + annotation = self.__annotations__[key] |
| 12 | + if issubclass(annotation, TpptSlideLayout): |
| 13 | + return annotation |
| 14 | + else: |
| 15 | + raise AttributeError(f"属性 {key} は {annotation} ではありません") |
| 16 | + |
| 17 | + |
| 18 | +@dataclass_transform( |
| 19 | + eq_default=True, |
| 20 | + order_default=False, |
| 21 | + field_specifiers=(), |
| 22 | +) |
| 23 | +class TpptSlideMaster(metaclass=TpptSlideMasterMeta): |
| 24 | + """スライドマスターのベースクラス""" |
| 25 | + |
| 26 | + _template_path: ClassVar[str | None] = None |
| 27 | + |
| 28 | + @classmethod |
| 29 | + def get_template_path(cls) -> str | None: |
| 30 | + """ |
| 31 | + テンプレートパスを取得する |
| 32 | + """ |
| 33 | + return cls._template_path |
| 34 | + |
| 35 | + |
| 36 | +class TpptSlideLayout: |
| 37 | + """スライドレイアウトのベースクラス""" |
| 38 | + |
| 39 | + @overload |
| 40 | + def __get__(self, instance: None, objtype: type[Any]) -> type[Self]: ... |
| 41 | + |
| 42 | + @overload |
| 43 | + def __get__(self, instance: object, objtype: type[Any]) -> Self: ... |
| 44 | + |
| 45 | + def __get__(self, instance: object | None, objtype: type[Any]) -> type[Self] | Self: |
| 46 | + if instance is None: |
| 47 | + return type(self) |
| 48 | + |
| 49 | + else: |
| 50 | + return self |
| 51 | + |
| 52 | + |
| 53 | +# 型変数を調整 |
| 54 | +TpptSlideMasterType = TypeVar("TpptSlideMasterType", bound=Type[TpptSlideMaster]) |
| 55 | +TpptSlideLayoutType = TypeVar("TpptSlideLayoutType", bound=Type[TpptSlideLayout]) |
| 56 | + |
| 57 | + |
| 58 | +class MyMasterSlide(TpptSlideLayout): ... |
| 59 | + |
| 60 | + |
| 61 | +class MyTitleSlide(TpptSlideLayout): ... |
| 62 | + |
| 63 | + |
| 64 | +class MyContentSlide(TpptSlideLayout): ... |
| 65 | + |
| 66 | + |
| 67 | +class MySlideMaster(TpptSlideMaster): |
| 68 | + master: MyMasterSlide |
| 69 | + title: MyTitleSlide |
| 70 | + totle_and_content: MyContentSlide |
| 71 | + |
| 72 | + |
| 73 | +# 以下のアサーションが通るようにせよ |
| 74 | +master: type[TpptSlideMaster] = MySlideMaster |
| 75 | +assert MySlideMaster.master == MyMasterSlide |
| 76 | +assert MySlideMaster.title == MyTitleSlide |
| 77 | +assert MySlideMaster.totle_and_content == MyContentSlide |
0 commit comments