Dynamic method

Daniel Nogradi nogradi at gmail.com
Tue Jul 10 10:07:57 EDT 2007


> 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' )



More information about the Python-list mailing list