next up previous contents
Next: 11 New in Release Up: 10.11 New Class Features Previous: 10.11.2 Trapping Attribute Access

10.11.3 Calling a Class Instance

If a class defines a method __call__ it is possible to call its instances as if they were functions. For example:

class PresetSomeArguments:
    def __init__(self, func, *args):
        self.func, self.args = func, args
    def __call__(self, *args):
        return apply(self.func, self.args + args)

f = PresetSomeArguments(pow, 2)    # f(i) computes powers of 2
for i in range(10): print f(i),    # prints 1 2 4 8 16 32 64 128 256 512
print                              # append newline



guido@cnri.reston.va.us