Object code parentheses (beginner)
-
24-05-2021 - |
سؤال
Why do I have to add the () at the end of f in this example?
def do_twice(f):
f()
f()
def print_spam():
print 'spam'
do_twice(print_spam)
spam
spam
Is it because function objects require a specified argument for functions?
المحلول
Why do I have to add the () at the end of f in this example?
Because f
is the function, and f()
actually calls the function. In your example do_twice(print_spam)
sends the do_twice
function the actual print_spam
function, not its result. If you would have used do_twice(print_spam())
, the do_twice
function would have received print_spam
's return value, which is None
نصائح أخرى
This is a language decision, python does require all function calls to have ()
to make things unambiguous. Take these few examples,
a = b
If b was a function, it would be ambiguous what a
would gets (the b function object or the result of calling b?).
a( b )
what would a
receive? (the b function or the result of calling b?). By requiring ()
, these problems do not arise