0

I have a class called timekeeper

class TimeKeeper():    
    def __init__(self):
        self.startTick = 0

    def StartClock(self, seconds, ev):
        self.startTick = pygame.time.get_ticks()
        self.seconds = seconds
        self.event = ev
    
    def CheckTime(self):
        timePassed = (pygame.time.get_ticks() - self.startTick)/1000
        if timePassed >= self.seconds and self.startTick != 0:
            self.startTick = 0
            try:
                self.event()
            except:
                pass
        return

And in it I pass an event which is a function that is called when a timer ends. However, I found an issue where if this event is a function that takes parameters (e.g. def foo(someVar) )

Timer1 = TimeKeeper()
Timer1.StartClock(4, foo)

I cant pass parameters through the class so that theyre called later. I tried adding the parameters inside of the input of the function as follows

Timter1.StartClock(4, foo('hello'))

but this ends up calling the function when the StartClock function is called rather than when the timer ends. How can I pass a variable through the class to a function without calling it (note that the number of variables may vary)?

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119

1 Answers1

2

foo('hello') calls foo immeidately, and its return value is passed to StartClock to be assigned to self.event. You still need to pass a callable that takes 0 arguments; you can do that with a lambda expression

Timter1.StartClock(4, lambda: foo('hello'))

or functools.partial

from functools import partial

Timer1.StartClock(4, partial(foo, 'hello'))
chepner
  • 497,756
  • 71
  • 530
  • 681