Method call of other classes in Python

I bind to creating a class containing a reference to another class method. I want to be able to call a method. This is basically a way to make callbacks.

My code works until I try to access the var class. When I run the code below, I get an 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()
+3
source share
3 answers

, WAY ( ;-). Python. - . - , . :

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

:

    self.method(*self.args)

:

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

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

In the code you called self.method.im_func(self.method), you should not pass the method as an argument, but the object from which this method was obtained. That is, it should beself.method.im_func(self.method.im_self, *self.args)

0
source

Source: https://habr.com/ru/post/1748580/


All Articles