How can I define class methods outside of the class?
Jeremy
jlconlin at gmail.com
Thu Dec 2 13:22:48 EST 2010
On Dec 2, 10:26 am, "bruno.desthuilli... at gmail.com"
<bruno.desthuilli... at gmail.com> wrote:
> On 2 déc, 15:45, Jeremy <jlcon... at gmail.com> wrote:
>
>
>
>
>
> > On Dec 1, 10:47 pm, James Mills <prolo... at shortcircuit.net.au> wrote:
>
> > > On Thu, Dec 2, 2010 at 3:36 PM, Jeremy <jlcon... at gmail.com> wrote:
> > > > I have some methods that I need (would like) to define outside of the
> > > > class. I know this can be done by defining the function and then
> > > > setting it equal to some member of an instance of the class. But,
> > > > because of the complexity of what I'm doing (I have to set many
> > > > functions as class methods) I would rather not do this. Can someone
> > > > show me how to do this? Is it even possible? Can decorators be used
> > > > here?
>
> > > Do you mean something like this ?
>
> > > @classmethod
> > > def foo(cls):
> > > print "I am the foo classmethod on %r" % cls
>
> > > class Foo(object):
> > > pass
>
> > > Foo.foo = foo
>
> > > cheers
> > > James
>
> > Thanks, James. That is almost exactly what I want. However, I want to avoid doing
>
> > Foo.foo = foo
>
> > Is this going to be possible?
>
> def patch(cls):
> def _patch(func):
> setattr(cls, func.__name__, func)
> return func
> return _patch
>
> class Foo(object): pass
>
> @patch(Foo)
> def bar(self):
> print self
>
> f = Foo()
> f.bar()
Yes! This is what I was looking for. Thanks!
Jeremy
More information about the Python-list
mailing list