Dynamic method

Alex Popescu the.mindstorm.mailinglist at gmail.com
Tue Jul 10 10:23:32 EDT 2007


On Jul 10, 5:07 pm, "Daniel Nogradi" <nogr... at gmail.com> wrote:
> > I have an issue I think Python could handle. But I do not have the knowledge
> > to do it.
>
> > Suppose I have a class 'myClass' and instance 'var'. There is function
> > 'myFunc(..)'. I have to add (or bind) somehow the function to the class, or
> > the instance. Any help, info or point of reference is wellcome....
>
> How about this (note the first argument 'self' which is the instance
> itself in the second case):
>
> def method_for_instance( message ):
>     print message
>
> def method_for_class( self, message ):
>     print message
>
> class myClass( object ):
>     pass
>
> inst = myClass( )
> inst.method = method_for_instance
>
> inst.method( 'hello' )
>
> myClass.method = method_for_class
>
> inst = myClass( )
> inst.method( 'hello' )

I think a solution may be using the new module and the function
instancemethod:

instancemethod(function, instance, class)
    This function will return a method object, bound to instance, or
unbound if instance is None. function must be callable.

./alex
--
.w( the_mindstorm )p.





More information about the Python-list mailing list