1. 程式人生 > >python內函式名加括號和不加括號的區別

python內函式名加括號和不加括號的區別

今天寫多執行緒程式的時候遇到了這樣的問題,
import thread
import time

def loop1():
    print  time.ctime()
    time.sleep(2)
    print time.ctime()

def loop2():
    print  time.ctime()
    time.sleep(4)
    print  time.ctime()

if __name__ == '__main__':
    thread.start_new_thread(loop1(),())
import thread
import time

def loop1():
    print  time.ctime()
    time.sleep(2)
    print time.ctime()

def loop2():
    print  time.ctime()
    time.sleep(4)
    print  time.ctime()

if __name__ == '__main__':
    thread.start_new_thread(loop1(),())
    thread.start_new_thread(loop2(),())
    time.sleep(6)

thread.start_new_thread(loop2(),()) time.sleep(6)

TypeError: first arg must be callable

返回的錯誤結果是這個,表示呼叫的要是一個可  支  配  的函式

後來我把程式碼改成了這樣

import thread
import time

def loop1():
    print  time.ctime()
    time.sleep(2)
    print time.ctime()

def loop2():
    print  time.ctime()
    time.sleep(4)
    print  time.ctime()

if __name__ == '__main__':
    thread.start_new_thread(loop1,())
    thread.start_new_thread(loop2,())
    time.sleep(6)


將thread後面呼叫的函式名改成了 loop1( 原來是loop1()),

在python中,函式名加(),表示返回的是一個函式的結果,不加括號表示的是對函式的呼叫。