I have a class where I want to be able to run children of the class at various frequencies: either every minute or every second. I use an Enum to decide whether I want to be called every second, every minute, both, or neither. Here's an example:
from enum import Flag, auto
import time
class FREQUENCY(Flag):
MINUTELY = auto() # call every_minute
SECONDLY = auto() # call every_second
class Parent:
def __init__(self, frequency):
self.frequency = frequency
def every_minute(self):
raise NotImplementedError()
def every_second(self):
raise NotImplementedError()
class HighFrequencyIdea(Parent):
def __init__(self):
super().__init__(FREQUENCY.SECONDLY) # oops!
def every_minute(self):
print("I expect to be called every minute but I put wrong frequency")
def every_second(self):
print("I am called every second")
if __name__ == "__main__":
obj = HighFrequencyIdea()
elapse = 0
while True:
time.sleep(1)
elapse += 1
if FREQUENCY.SECONDLY in obj.frequency:
obj.every_second()
if FREQUENCY.MINUTELY in obj.frequency and elapse % 60 == 0:
obj.every_minute()
Is there a way to prevent children of the class Parent from implementing something that they haven't set the correct frequency for (in this case make some error for implementing every_minute despite having a frequency of FREQUENCY.SECONDLY -- either having a frequency of FREQUENCY.SECONDLY|FREQUENCY.minutely or implementing just every_second in HighFrequencyIdea would be acceptable but implementing every_minute while not having FREQUENCY.minutely is unacceptable).