pythonobject-code

Object code parentheses (beginner)


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?


Solution

  • 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