为什么线程使用 class 作为参数?
Why is Threading using the class as an arg?
我正在尝试使用线程 运行 具有多个参数的函数。每当我尝试执行代码时,它都会说我为该函数提供了太多参数。在我最后一次尝试中,我使用了 1 less 个参数而不是所需的函数,瞧,它通过使用 class 本身作为参数来工作。这是我的代码。
import threading
import sys
import tkinter
class Window():
'''Class to hold a tkinter window'''
def __init__(self, root):
'''Makes a button'''
button1 = tkinter.Button(root,
text = ' Print ',
command = self.Printer
)
button1.pack()
def Function(x,y,z):
'''function called by the thread'''
print(x)
print(y)
print(z)
def Printer(self):
'''function called by the button to start the thread'''
print('thread started')
x = threading.Thread(target=self.Function, args=('spam', 'eggs'))
x.daemon = True
x.start()
root = tkinter.Tk()
Screen = Window(root)
root.mainloop()
这是结果输出。通常我会从中预料到某种错误;请注意,当函数调用三个参数时,我只指定了两个参数!
thread started
<__main__.Window object at 0x000001A488CFF848>
spam
eggs
发生这种情况的原因是什么?在 IDLE 中使用 python 3.7.5,如果这有所作为的话。
Function
是一种方法,因此调用 self.function 隐式提供 self 作为第一个参数。如果这不是您想要的行为,请考虑切换到静态方法或使用函数。
我正在尝试使用线程 运行 具有多个参数的函数。每当我尝试执行代码时,它都会说我为该函数提供了太多参数。在我最后一次尝试中,我使用了 1 less 个参数而不是所需的函数,瞧,它通过使用 class 本身作为参数来工作。这是我的代码。
import threading
import sys
import tkinter
class Window():
'''Class to hold a tkinter window'''
def __init__(self, root):
'''Makes a button'''
button1 = tkinter.Button(root,
text = ' Print ',
command = self.Printer
)
button1.pack()
def Function(x,y,z):
'''function called by the thread'''
print(x)
print(y)
print(z)
def Printer(self):
'''function called by the button to start the thread'''
print('thread started')
x = threading.Thread(target=self.Function, args=('spam', 'eggs'))
x.daemon = True
x.start()
root = tkinter.Tk()
Screen = Window(root)
root.mainloop()
这是结果输出。通常我会从中预料到某种错误;请注意,当函数调用三个参数时,我只指定了两个参数!
thread started
<__main__.Window object at 0x000001A488CFF848>
spam
eggs
发生这种情况的原因是什么?在 IDLE 中使用 python 3.7.5,如果这有所作为的话。
Function
是一种方法,因此调用 self.function 隐式提供 self 作为第一个参数。如果这不是您想要的行为,请考虑切换到静态方法或使用函数。