Method behavior for user-created class instances
Larry Bates
larry.bates at websafe.com`
Mon Jul 14 21:04:14 EDT 2008
crazychimp132 at gmail.com 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.
>
> Eg.
>
> class foo:
> def __call__(self, inst): pass
>
> class bar:
> meth = foo()
>
> such that bar().meth() will not raise an exception for too few
> arguments (because the inst argument in foo.__call__ is implicitly set
> to the bar instance). 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. The need for this arises out of
> the implementation of a function decorator as a class.
>
> Thanks.
While it is not clear "why" you would want this, I believe this works.
If not, take a look at staticmethods or classmethods, they might work for you.
>>> class foo(object):
... def __call__(self, inst):
... print "foo.__call__", inst
...
>>> class bar:
... def __init__(self):
... self.foo = foo()
... self.meth = self.foo.__call__
...
>>> b = bar()
>>> b.meth(1)
foo.__call__ 1
-Larry
More information about the Python-list
mailing list