Method behavior for user-created class instances

bruno.desthuilliers at bruno.desthuilliers at
Tue Jul 15 15:53:31 CEST 2008

On 15 juil, 01:24, crazychimp... at wrote:
> Greetings.
> I am looking for a way to achieve method behavior for a class I
> created. That is, it has a __call__ method,  so can be called like a
> function. But I also want it to be treated as a method when it appears
> in a class body.

You need to implement the descriptor protocol the same way the
function type do.

import types

class Foo(object):
    def __call__(self, instance):
        print "%s - %s" % (self, instance)

    def __get__(self, instance, cls):
        return types.MethodType(self, instance, cls)

class Bar(object):
    foo = Foo()

b = Bar()

> I know this has to do with writing the __get__
> method of foo, but I am wondering if there is perhaps some class I can
> just inherit from to get the proper __get__, which behaves identically
> to that of regular Python functions.

Extending types.FunctionType doesn't work OOTB (there's some
incompatibility wrt/ metaclasses)

More information about the Python-list mailing list