Redefining __call__ in an instance

John Roth newsgroups at jhrothjr.com
Fri Jan 16 04:09:48 CET 2004


"Robert Ferrell" <ferrell at diablotech.com> wrote in message
news:73b00f0c.0401151529.676347b6 at posting.google.com...
> I have a question about assigning __call__ to an instance to make that
> instance callable.  I know there has been quite a bit of discussion
> about this, and I've read all I can find, but I'm still confused.
>
> I'd like to have a factory class that takes a string argument and returns
> the appropriate factory method based on that string.  I'd like the
> instances to be callable.  Like this:
>
> fact = Factory('SomeThing')
> aSomeThing = fact(some args)
>
> anotherFact = Factory('SomeThingElse')
> anotherThing = anotherFact(some other args)
>
> The way I thought to do this was to assign the __call__ attribute of
> the fact instance to the appropriate factory method in __init__.  That
does not
> work, as many others have pointed out.  I know there are workarounds.
> The appended code shows the variants I know of.  I can use one of
> them, but they are not quite what I am looking for.
>
> Have I missed the key message that explains how to make new-style
> classes callable, with the called method unique to each instance?

Basically, the system does not look in the instance for the __call__
method for new style classes. I'm not sure why not, or where this
is defined, but that's the way it works.

To get a different callable for each instance, you need to do something
like this:

class fubar(object):
    def __init__(self, callable):
        self.myfunc = callable

    def __call__(self, *a, **b):
        self.myfunc(*a, **b)



>
> thanks,
> -robert





More information about the Python-list mailing list