开发者

Call another classes method in 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
  开发者_C百科      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()


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


Why not use this:

    self.method(*self.args)

instead of this:

    if self.args:
        self.method.im_func(self.method, *self.args)

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


In your code you were calling self.method.im_func(self.method) - you shouldn't have been passing the method as argument but the object from which that method came. I.e. should have been self.method.im_func(self.method.im_self, *self.args)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜