advanced-python-homework-2023/equipment/turtle_device.py
2023-12-15 00:25:07 +03:00

58 lines
1.9 KiB
Python

from turtle import Turtle
from typing import Any, Collection, Optional
from controls.device import SynchronyDevice, TraitDescriptor, DeviceLifecycleState
class TurtleDevice(SynchronyDevice):
def open(self):
self.state == DeviceLifecycleState.OPEN
self.turtle = Turtle()
super().open()
def close(self):
del self.turtle
super().close()
@property
def trait_descriptors(self):
traits = [attribute for attribute in vars(self.turtle).items()
if (attribute[0].startswith('_') == False)]
self.traits = [TraitDescriptor(*tr) for tr in traits]
return self.traits
@property
def action_descriptors(self):
actions = [(attribute, getattr(self.turtle, attribute)) for attribute in dir(self.turtle)
if (attribute.startswith('_') == False)]
self.actions = [TraitDescriptor(*ac) for ac in actions]
return self.actions
def read(self, trait_name):
collection = self.traits
return ([collection[i].info for i in range(len(collection))
if collection[i].name == trait_name])
def write(self, trait_name: str, value: Any) -> bool:
collection = self.traits
for i in range(len(collection)):
if collection[i].name == trait_name:
collection[i].info=value
def execute(self, action_name: str, *args, **kwargs):
if self.state == DeviceLifecycleState.INIT:
self.open()
execution = getattr(self.turtle, action_name)
execution(int(*args), **kwargs)
def invalidate(self, trait_name: str):
return super().invalidate(trait_name)
def __getitem__(self, trait_name: str) -> Any | None:
collection = self.traits
return ([collection[i] for i in range(len(collection))
if collection[i].name == trait_name])