user1999094
user1999094

Reputation: 41

Is there a way to make sure a function is overwritten?

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).

Upvotes: 2

Views: 72

Answers (2)

scr
scr

Reputation: 962

You could add a property to the class called last_call_time that stores the time of the last call. Then when being called with the 1 minute caller, if the difference between current time and last_call_time isn't 60s or more you can pop an error.

Upvotes: 0

Zazaeil
Zazaeil

Reputation: 4119

That's a badly designed abstraction. How about having single method named tick(...) that does whatever is supposed to be done along with a frequency() property?

Upvotes: 3

Related Questions