Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #### Some Python code
- from dataclasses import dataclass
- from enum import Enum
- from typing import Union
- class ButtonType(Enum):
- color_sel = 1
- room_sel = 2
- class HSV(Enum):
- h = 1
- s = 2
- v = 3
- # [1] Opaque payload
- @dataclass
- class HSVColorPayload:
- type: HSV
- value: int
- @dataclass
- class RoomPayload:
- room_no: int # Enum in actual life
- @dataclass
- class ButtonEvent:
- btype: ButtonType
- payload: Union[HSVColorPayload, RoomPayload]
- def do_color_sel(p: HSVColorPayload): pass
- def do_color_sel(p: RoomPayload): pass
- def process_button_event(e: ButtonEvent) -> None:
- handlers = {
- ButtonType.color_sel: do_color_sel,
- ButtonType.room_sel: do_room_self,
- }
- handler = handler[e.btype]
- handler(e.payload)
- # [1] Subclassing
- @dataclass
- class ButtonEvent:
- btype: ButtonType
- @dataclass
- class ColorEvent(ButtonEvent):
- type: HSV
- value: int
- @dataclass
- class RoomEvent(ButtonEvent):
- room_no: int
- def do_color_sel(e: ColorEvent): pass
- def do_color_sel(e: RoomEvent): pass
- def process_button_event(e: ButtonEvent) -> None:
- handlers = {
- ButtonType.color_sel: do_color_sel,
- ButtonType.room_sel: do_room_self,
- }
- handler = handler[e.btype]
- handler(e)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement