# callback
# Walker M. White (wmw2)
# November 8, 2012
"""Module that shows how to use and implement a callback function."""


class Caller(object):
    """Instance is an object that stores an object to be called later."""
    # Reference to a callback function
    _callback = None
    
    def __init__(self,callback):
        """Creates a Caller with foo() set to use callback."""
        self._callback = callback
    
    def repeat(self,n):
        """Call the callback, if it exists, n times.
        
        Precondition: n is a nonnegative int"""
        assert type(n) == int and n >=0, `n`+' is not a nonnegative int'
        # do nothing if callback is None
        if self._callback is None:
            return
        
        for i in range(n):
            self._callback() # Note the parentheses.  NOW we are calling it.


def function1():
    """Sample function to use as a call back."""
    print 'Hello World!'
    
def function2():
    """Sample function to use as a call back."""
    print 'Good bye World!'
    
def function3(n):
    """Sample function to use as a call back."""
    return n+1

# Test Code
if __name__ == '__main__':
    # Create a caller for function1
    c = Caller(function1) # Note use of function1 WITHOUT PARENS
    c.repeat(3)
    
    # Create a caller for function2
    c = Caller(function2) # Note use of function2 WITHOUT PARENS
    c.repeat(4)
    
    # This will cause an error.
    c = Caller(function3)
    c.repeat(2)