functors

Troy Melhase troy at gci.net
Tue Jul 1 21:46:28 EDT 2003


Tom Plunket wrote:
> What I want (being a C++ coder <g>), is to be able to create an
> object that I is callable.  

Hi Tom:

I'm not quite certain how you intend to use the classes you provided in your
original post, but the answer to your question is to define a __call__
method in your class.  Untested example:

class SomeClass:
    def __init__(self, factor):
        self.factor = factor

    def __call__(self, value):
        return value * self.factor

my_object = SomeClass(3)
print my_object(4)

You can learn more about __call__ and other special functions for classes in
the Language Reference (section 3.3 for python2.2).

Good luck,
troy




More information about the Python-list mailing list