First of all I would like you to know that I read different topics about: cyclic import, cycling type hints and so on. According to this answer we can notice that:
States store a reference to the context object that contains them.
And I need exactly such solution. So I prepared two demo files, state.py:
from abc import ABC, abstractmethod
class State(ABC):
@abstractmethod
def set_screen_brightness(self, computer: Laptop) -> None:
pass
class PowerSupplyOn(State):
def set_screen_brightness(self, computer: Laptop) -> None:
computer._set_max_brightness()
class PowerSupplyOff(State):
def set_screen_brightness(self, computer: Laptop) -> None:
computer._set_min_brightness()
and laptop.py:
from states import *
class Laptop:
def __init__(self) -> None:
self.state = PowerSupplyOn()
self.adjust_brightness_screen()
def adjust_brightness_screen(self) -> None:
self.state.set_screen_brightness(self)
def _set_max_brightness(self) -> None:
print('Brightness level: 100%')
def _set_min_brightness(self) -> None:
print('Brightness level: 15%')
Going to the point - I stuck. Of course I can't import Laptop inside state.py (cyclic imports). On the other hand I need type hints. Alternatively, I can remove Laptop hints from method's headers (but I need them) or make them as strings, i.e. 'Laptop'. Or maybe I shouldn't pass back-reference to the context (Laptop class) at all?
How to deal with this issue?
Aucun commentaire:
Enregistrer un commentaire