简体   繁体   English

将函数传递给Python 3中的类

[英]Passing a function to a class in Python 3

well it doesn't shows any errors once i add self.methodToRun = function yet the function doesn't get called.(This is what happens 好吧,一旦我添加self.methodToRun =函数,它不会显示任何错误,但该函数不会被调用。(

>>> func()
1
>>> ================================ RESTART ================================
>>> 
>>> tt = timer_tick(1,func)
>>> tt.start()
>>> )

here's the code 这是代码

import time

def func():
    print('1')

class timer_tick:

    def __init__(self, num, function):
        self.delay = num
        self.methodToRun = function
        self.timercondition = False
    def start(self):
        timercondition = True
        self.timer()
    def timer(self):
        while self.timercondition:
            self.methodToRun()
            time.sleep(self.delay)

    def stop(self):
        timercondition = False

def method1():
    return 'hello world'

def method2(methodToRun):
    result = methodToRun()
    return result

well I discovered this while writing a stopwatch program, that a timer effect can be achieved by the tkinter.Tk.after() function. 我在编写秒表程序时发现了这一点,可以通过tkinter.Tk.after()函数实现计时器效果。 I was able to add control to stop,pause and reset the timer with it. 我能够添加控件以停止,暂停和重置计时器。

import tkinter
import random
import time

frame = tkinter.Tk()
frame.title("Stopwatch")
frame.geometry('500x300')

t='00:00.0'
helv30 = ('Helvetica', 30)
num = 0
timer = 1


def timerhand():
    global num,n
    num += 1
    formate(num)
def formate(num):
    global t,n
    if (get_seconds(num) >= 0 and get_seconds(num)<10):
     if (num%100)%10 == 0 and (num//600) < 10 :
       t ='0'+ str(get_minutes(num)) + ':'+'0' + str(get_seconds(num))+'.0'
     elif (num//600) < 10:
       t ='0'+ str(get_minutes(num)) + ':'+'0' + str(get_seconds(num))
     elif (num%100)%10 == 0:
       t =str(get_minutes(num)) + ':'+'0' +  str(get_seconds(num))+'.0'
     else:
       t = str(get_minutes(num)) + ':'+'0' + str(get_seconds(num))
    else:
     if (num%100)%10 == 0 and (num//600) < 10 :
       t ='0'+ str(get_minutes(num)) + ':' + str(get_seconds(num))+'.0'
     elif (num//600) < 10:
       t ='0'+ str(get_minutes(num)) + ':' + str(get_seconds(num))
     elif (num%100)%10 == 0:
       t =str(get_minutes(num)) + ':' +  str(get_seconds(num))+'.0'
     else:
       t = str(get_minutes(num)) + ':' + str(get_seconds(num))
def get_minutes(num):
    return (num//600)
def get_seconds(num):
    return (num%600)/10

def stop():
    global timer,t,num
    timer = 0
    t = '00:00.0'
    num = 0
def pause():
    global timer,t
    timer = 0

def start():
    global timer
    timer = 1
    clock()

canvas1 = tkinter.Canvas(frame,width = 300, height = 100,bg = 'black')
t_message = canvas1.create_text(150,50, text = t , fill = 'blue', font = helv30 )

b1= tkinter.Button(frame,text = "Stop",command = stop)
b1.pack(side ="bottom")

b2= tkinter.Button(frame,text = "Start",command = start)
b2.pack(side ="bottom")

b2= tkinter.Button(frame,text = "Pause",command = pause)
b2.pack(side ="bottom")


#here is the time function implementation

def clock():
    global canvas1,t_message
    timerhand()

    canvas1.itemconfig(t_message, state = 'hidden')
    t_message = canvas1.create_text(150,50, text = t , fill = 'blue', font = helv30 )
    canvas1.pack()    

    if timer == True:
        frame.after(100,clock)


clock()


canvas1.pack()


frame.mainloop()

so I was looking for ways to achieve this without the tkinter module 所以我一直在寻找没有tkinter模块的方法

You are converting the function to a string: 您正在将函数转换为字符串:

self.methodToRun = str(function)

Therefore when you call it: 因此,当您调用它时:

self.methodToRun()

You are trying to call a string, which won't work. 您正在尝试调用一个字符串,该字符串不起作用。 You can just store the function like any other parameter: 您可以像存储其他任何参数一样存储该函数:

self.methodToRun = function

And pass as you would any other argument: 像其他任何参数一样传递:

tt = timer_tick(my_num, my_func)

You should probably also be storing the delay and timercondition as instance attributes: 您可能还应该将delaytimercondition存储为实例属性:

def __init__(self, num, function):
    self.delay = num
    self.methodToRun = function
    self.timercondition = False

Edit : your updated version has two problems: 编辑 :您的更新版本有两个问题:

  1. You refer to timercondition , not self.timercondition , in start ; 您在start是指timercondition而不是 self.timercondition and
  2. timer will run forever, as it never returns control to allow you to call stop . timer将永远运行,因为它永远不会返回控制权以允许您调用stop

The former is easy to solve, the latter much less so. 前者很容易解决,而后者则不那么容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM