在 Python 中,调用名为 check_values 的函数的线程创建如下:
checking_thread = threading.Thread(target=check_values)
我的问题是为什么省略了 check_values 的括号?
如果包含它们会怎样?
请您参考如下方法:
Python 中的函数是一流的对象。它们可以作为参数传递给函数,分配给变量,或者通过“调用”它们来调用。调用函数的语法是引用函数名并紧跟其后的圆括号。参数可以通过在括号之间列出来传递给函数。示例:
def check_values(x=0):
print(x)
>>> check_values
<function check_values at 0x7fae489c7ea0>
>>> type(check_values)
<class 'function'>
>>> check_values()
0
>>> check_values(10)
10
>>> print(check_values)
<function check_values at 0x7fae488df400>
所以 check_values 是对函数对象的引用,您可以通过键入它的名称来查看它是一个对象。可以使用括号调用它,在这种情况下使用可选参数。最后,您可以看到该函数作为参数传递给 print() 函数。
所以回答你的问题:
checking_thread = threading.Thread(target=check_values)
这将对名为 check_values 的函数的引用作为 target 参数传递给 threading.Thread 函数 without 调用函数 check_values。
如果你想让 threading.Thread 调用带有参数的函数,那么你需要单独传递它们,例如
checking_thread = threading.Thread(target=check_values, args=(100,))
