有没有一种方法可以在不传递参数的情况下调用函数?

wae*_*raf 4 python security function

我是信息安全方面的新手,我试图自学如何使用 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()
Run Code Online (Sandbox Code Playgroud)

当我试图理解这段代码时,我发现函数“OnKeyboardEvent”的调用没有给出它的参数

hm.KeyDown = OnKeyboardEvent
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:python 有没有办法在不给参数的情况下调用函数?

Phi*_*nge 5

在Python中,函数名相当于存储函数的变量。换句话说:您可以定义一个名为的函数foo并将其存储/引用在第二个变量中bar

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

bar = foo

bar() # prints: foo!
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您仅定义该函数OnKeyboardEvent(event)并将其引用保存在hm.KeyDown

该函数的调用仅在您按下键盘按键时发生,并且在 hm 中从事件处理程序内部调用。事件处理程序将事件对象传递给函数。

回答有关不带参数调用函数的问题。对于所有参数都设置默认值的函数是可能的,例如:

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

print(foo()) # prints: default string
print(foo("hello world!")) # prints: hello world!
Run Code Online (Sandbox Code Playgroud)