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'

1
  • 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. Commented Jan 23, 2018 at 5:20

1 Answer 1

3

You need to create an instance of Scheduler.

x = Scheduler()

instead of

x = Scheduler
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you brother Bill ! x = Scheduler() will create an instance. If you don't mind can you tell me what x = Scheduler does?
x = Scheduler creates another name to the class Scheduler. So you could do: AnotherSchedulerClass = Scheduler; x = AnotherSchedulerClass();.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.