How can I define class methods outside of the class?

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Thu Dec 2 12:19:53 EST 2010


On 2 déc, 06:36, 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

<OT>
"assignement" or "binding" might be the terms you were looking for
here ;)

Also in Python we talk about "attributes", not "members"
</OT>

> of an instance of the class.

What you describe here will not "define class methods", nor even
instance methods FWIW - it will only make the function an attribute of
the instance, but won't turn the function into a method (IOW: the
function won't get the instance as first argument).

Also and while we're at it, a Python "classmethod" is something
special - it's a method that can be called on either an instance or
the class itself, and takes the class - not the instance - as first
argument.

> 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?

To "no do this" ? Yes, certainly <g>

More seriously: if your problem is to dynamically add a bunch of
methods to an existing *class*, it's quite easy - just import the
class and assign your functions to it, ie:

from otherlib import OtherClass

def foo(self):
   print "%s.foo" % self


OtherClass.foo = foo

And voila, The "foo" method is now available to all (even already
existing) instances of OtherClass.

If this doesn't answer your question, please provide more context.

>  Can decorators be used
> here?

What for ?




More information about the Python-list mailing list