How to use a decorator in a class

I know there is a similar question, but my scenario is somehow different: see codes:

class MyClass(object):
    def __init__(self, log_location)
        self.logs = logging(log_location) # create log object by the log_location, this object should be used by the decorator fucntion

    def record_log(log_object): 
        """ this is the decorator function
        """
        def deco(func):
            def wrap(*args, **kwargs):
                rs = func()

                # use log object to record log
                if rs:
                    log_object.record('success')
                else:
                    log_object.record('fail')

            return wrap
        return deco

   @record_log(self.logs) 
   def test(self):
       rs = do_some_thing
       if rs:
            return True
       return False

def main():
    my_class = MyClass()
    my_class.test()   

But there is such an error:

@record_log(self.logs)
NameError: name 'self' is not defined

Hos should use the instance self.logs attribute in a decorator function in a scenario like this?

Many thanks!

+4
source share
2 answers

There are several objections in your code:

  • deco()is redundant. You can directly return wrapfrom record_log().

  • MyClass, log_object , self.logs . , .

  • .

  • self.

, :

class MyClass(object):
    def __init__(self, log_location):
        self.logs = logging(log_location)

    def record_log(func):
        """ this is the decorator function
        """
        def wrap(self):
            rs = func(self)
            # use log object to record log
            if rs:
                print 1
                self.logs.record('success')
            else:
                print 2
                self.logs.record('fail')
            return rs
        return wrap

    @record_log
    def test(self):
       rs = do_some_thing
       if rs:
            return True
       return False
+1

self self . @record_log ( ) , main, .. , - MyClass - , , MyClass ! ,

@record_log(self.logs) 
def test(self, n):

test = record_log(self.logs)(test)

, test __init__, ..

def __init__(self, log_location)
    self.logs = logging(log_location)
    self.test = record_log(self.logs)(self.test)

, func . , , , ( ).

def record_log(log_object): 
    def deco(func):
        def wrap(*args, **kwargs):
            rs = func(*args, **kwargs)   # pass parameters
            if rs:
                log_object.record('success')
            else:
                log_object.record('fail')
            return rs   # return result
        return wrap
    return deco
+1

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


All Articles