Jramak wrote:
Hello
I'm confused by callbacks. I would really appreciate any introduction or help in understanding the concept of callbacks.

By example:

def callback(nums):
    """ The callback function """
    return sum(nums) * 2

def another_callback(nums):
    """ Yet another callback function """
    return sum(nums) * 3

def strange_sum(nums, cb):
    """
    Returns the sum, if less than 10
    else returns the result of calling the callback function cb(),
    which must accepts one list argument
    """
    if sum(nums) > 10:
        return sum(nums)
    else:
        return cb(nums)

print strange_sum([1, 3, 4, 2, 4], callback)
print strange_sum([3, 5, 4, 2], another_callback)

So basically, a callback is a function that you passes as an argument (to another function) that may be called when a certain condition happens. In GUI-related stuff, callbacks are called when a certain events happens (e.g. a button is clicked).

For the note, there are two main reasons why you want to pass a function to another function:
1. For callbacks, as explained and reasoned above.
2. To modify the passed functions, this case is known as decorator.

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to