Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call another classes method in Python

Tags:

python

I'm tying to create a class that holds a reference to another classes method. I want to be able to call the method. It is basically a way to do callbacks.

My code works until I try to access a class var. When I run the code below, I get the error What am I doing wrong?

Brian

import logging

class yRunMethod(object):
    """
    container that allows method to be called when method run is called 
    """

    def __init__(self, method, *args):
        """
        init
        """

        self.logger = logging.getLogger('yRunMethod')
        self.logger.debug('method <%s> and args <%s>'%(method, args))

        self.method = method
        self.args   = args

    def run(self):
    """
    runs the method
    """

        self.logger.debug('running with <%s> and <%s>'%(self.method,self.args))

        #if have args sent to function
        if self.args:
            self.method.im_func(self.method, *self.args)

        else:
            self.method.im_func(self.method)

if __name__ == "__main__":  
    import sys

    #create test class
    class testClass(object):
        """
        test class 
        """

        def __init__(self):
            """
            init
            """

            self.var = 'some var'

        def doSomthing(self):
            """

            """

            print 'do somthing called'
            print 'self.var <%s>'%self.var

    #test yRunMethod
    met1 = testClass().doSomthing
    run1 = yRunMethod(met1)
    run1.run()
like image 520
brian Avatar asked Apr 12 '26 09:04

brian


1 Answers

I think you're making this WAY too hard on yourself (which is easy to do ;-). Methods of classes and instances are first-class objects in Python. You can pass them around and call them like anything else. Digging into a method's instance variables is something that should almost never be done. A simple example to accomplish your goal is:

class Wrapper (object):
    def __init__(self, meth, *args):
        self.meth = meth
        self.args = args

   def runit(self):
       self.meth(*self.args)

class Test (object):
    def __init__(self, var):
        self.var = var
    def sayHello(self):
        print "Hello! My name is: %s" % self.var

t = Test('FooBar')
w = Wrapper( t.sayHello )

w.runit()
like image 105
Rakis Avatar answered Apr 14 '26 23:04

Rakis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!