1

I would like to understand how to pass an external function to a class method. For example say I am trying to call a function 'job' every second.

import schedule
import time

def set_timer_minutes(func):
    schedule.every(1/60).minutes.do(func)

def job():
    print("I'm working...")

set_timer_minutes(job)
while 1:
    schedule.run_pending()
    time.sleep(1)

The above code prints 'I'm working' every second. But if I try to put it in a class

class Scheduler:
    def set_timer_minutes(self,func):
        schedule.every(1/60).minutes.do(func)
        while 1:
            schedule.run_pending()
            time.sleep(1)

def job():
    print("I'm working...")

x= Scheduler
x.set_timer_minutes(job)

I get

TypeError: set_timer_minutes() missing 1 required positional argument: 'func'

BharathRao
  • 1,846
  • 1
  • 18
  • 28
AdR
  • 197
  • 1
  • 3
  • 10
  • Where is the class method? What you have is an instance method. You may just be unaware of the python specific terminology relating to static, class and instance methods. One related link is [this](https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner). – Paul Rooney Jan 23 '18 at 05:20

1 Answers1

3

You need to create an instance of Scheduler.

x = Scheduler()

instead of

x = Scheduler
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • Thank you brother Bill ! x = Scheduler() will create an instance. If you don't mind can you tell me what x = Scheduler does? – AdR Jan 23 '18 at 05:25
  • `x = Scheduler` creates another name to the class Scheduler. So you could do: `AnotherSchedulerClass = Scheduler; x = AnotherSchedulerClass();`. – Bill Lynch Jan 23 '18 at 06:42