2017-07-29 182 views
1

蔭信息安全新IAM試圖教我自己如何建立與Python簡單的鍵盤記錄,我發現這個代碼在一個網站:有沒有辦法在不傳遞參數的情況下調用函數?

import pythoncom, pyHook 

def OnKeyboardEvent(event): 
    print 'MessageName:',event.MessageName 
    print 'Message:',event.Message 
    print 'Time:',event.Time 
    print 'Window:',event.Window 
    print 'WindowName:',event.WindowName 
    print 'Ascii:', event.Ascii, chr(event.Ascii) 
    print 'Key:', event.Key 
    print 'KeyID:', event.KeyID 
    print 'ScanCode:', event.ScanCode 
    print 'Extended:', event.Extended 
    print 'Injected:', event.Injected 
    print 'Alt', event.Alt 
    print 'Transition', event.Transition 
    print '---' 

    # return True to pass the event to other handlers 
    return True 

# create a hook manager 
hm = pyHook.HookManager() 
# watch for all mouse events 
hm.KeyDown = OnKeyboardEvent 
# set the hook 
hm.HookKeyboard() 
# wait forever 
pythoncom.PumpMessages() 

,雖然我試圖理解這個代碼,我發現功能「OnKeyboardEvent」的不給調用它的參數

hm.KeyDown = OnKeyboardEvent 

所以我的問題是: 有沒有在Python的方式來調用一個函數,而不給它的參數?

+0

'hm.KeyDown = OnKeyboardEvent'不是函數調用。檢查[this](https://stackoverflow.com/questions/10354163/assigning-a-function-to-a-variable)出 – jacoblaw

+0

@jacoblaw非常感謝 –

回答

1

在python中,函數名相當於存儲函數的變量。換句話說:你可以定義一個名爲foo和存儲功能/在第二個變量bar引用它:

def foo(): 
    print("foo!") 

bar = foo 

bar() # prints: foo! 
你的情況

,您只定義功能OnKeyboardEvent(event)並保存在hm.KeyDown

它的一個參考

只有當您按下鍵盤鍵並在事件處理程序的hm內部調用函數調用時纔會發生。並在那裏事件處理程序傳遞一個事件對象給函數。

回答你有關不帶參數調用函數的問題。 有可能爲其中所有參數的默認值設置 如功能:

def foo(bar = "default string"): 
    print(bar) 

print(foo()) # prints: default string 
print(foo("hello world!")) # prints: hello world! 
+0

明白,iam非常感謝非常感謝 –

0

當你做hm.KeyDown = OnKeyboardEvent你沒有調用函數OnKeyboardEvent,你只是將該函數分配給hm.KeyDown。稍後pyHook.HookManager會在任何KeyboardEvent發生時爲您調用該方法。

+0

非常感謝你... –

0

調用函數:

OnKeyboardEvent() 

分配的功能,比方說,一個變量(不調用函數馬上):

var = OnKeyboardEvent 

和你只是將功能分配到OnKeyboardEvent pyHook.HookManager(的)的KeyDown財產

hm = pyHook.HookManager() 
hm.KeyDown = OnKeyboardEvent 
+0

@AdriánKálazi –

相關問題