Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to call function without passing its parameters?

Iam new in information security and iam trying to teach my self how to build a simple keylogger with python, i found this code in a site :

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()

and while i was trying to understand this code, i found the call of the function 'OnKeyboardEvent' without giving it's parameter

hm.KeyDown = OnKeyboardEvent

So my question is : is there a way in python to call a function without giving it the parameter ?

like image 452
wael ashraf Avatar asked Oct 29 '25 01:10

wael ashraf


2 Answers

in python a function name is equivalent to a variable in which a function is stored. in other words: you can define a function called foo and store / reference it in a second variable bar:

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

bar = foo

bar() # prints: foo!

in your case, you are only defining the function OnKeyboardEvent(event) and you save a reference of it in hm.KeyDown

the call of the function happens only if you press a keyboard key and is called internally in hm from an event handler. and there the event handler passes down an event object to the function.

to answer your question concerning calling functions without their parameters. it's possible for functions where default values for all parameters are set e.g.:

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

print(foo()) # prints: default string
print(foo("hello world!")) # prints: hello world!
like image 56
Philipp Lange Avatar answered Oct 31 '25 16:10

Philipp Lange


Calling a function:

OnKeyboardEvent()

Assigning a function to let's say a variable (this doesn't call the function immediately):

var = OnKeyboardEvent

and your is just assigning the function OnKeyboardEvent to pyHook.HookManager('s) KeyDown property

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
like image 41
Adrián Kálazi Avatar answered Oct 31 '25 17:10

Adrián Kálazi