How can I use a class instance variable as an argument to a method decorator in Python?

How can I use a class instance variable as an argument to a method decorator in Python? Below is a minimal example of what I'm trying to do. It obviously fails because the decorator function does not have access to the instance link, and I have no idea how to access the link from the decorator.

def decorator1(arg1):
    def wrapper(function):
        print "decorator argument: %s" % arg1
        return function
    return wrapper

class Foo(object):
    def __init__(self, arg1):
        self.var1 = arg1

    @decorator1(self.var1)
    def method1(self):
        print "method1"

foo = Foo("abc")
foo.method1()
+5
source share
5 answers

; , ( - ). , "" , "" :

def get_decorator(arg1):
    def my_decorator(function):
        print "get_decorator argument: %s" % arg1
        return function
    return my_decorator

class Foo(object):
    def __init__(self, arg1):
        self.var1 = arg1
        self.method1 = get_decorator(self.var1)(self.method1)

    def method1(self):
        print "method1"

foo = Foo("abc")
foo.method1()

, ; "", .. , () , wrapper, decorator1.

+9

"" , . "decorator1" . self.var1 , :

def decorator(function):
  def wrapper(self,*args,**kwargs):
    print "Doing something with self.var1==%s" % self.var1
    return function(self,*args,**kwargs)
  return wrapper

class Foo(object):
  def __init__(self, arg1):
    self.var1 = arg1

  @decorator
  def method1(self):
    print "method1"

foo = Foo("abc")
foo.method1()

, , :

class decorator:
  def __init__(self,varname):
      self.varname = varname
  def __call__(self,function):
    varname=self.varname
    def wrapper(self,*args,**kwargs):
      print "Doing something with self.%s==%s" % (varname,getattr(self,varname))
      return function(self,*args,**kwargs)
    return wrapper

:

  @decorator("var1")
+5

, , .

+1

.

class Foo(object):
    def __init__(self, arg1):
        self.var1 = arg1

    def method1(self):
        self.lock()
        try:
            self.do_method1()
        except Exception:
            pass # Might want to log this
        finally:
            self.unlock()

    def do_method1(self):
        print "method1"

    def lock(self):
        print "locking: %s" % self.arg1

    def unlock(self):
        print "unlocking: %s" % self.arg1

do_method1, "". with.

, . , .

+1

, .

, . , , , .

, , Python ( 2.7) . context manager, , .

from contextlib import contextmanager

def lock_file(file):
    print('File %s locked' % file)

def unlock_file(file):
    print('File %s unlocked' % file)

@contextmanager
def file_locked(arg1):
    lock_file(arg1)
    yield
    unlock_file(arg1)

class Foo(object):
    def __init__(self, arg1):
        self.var1 = arg1

    def method1(self):
        with file_locked(self.var1) as f:
            print "method1"

foo = Foo("abc")
foo.method1()
0

All Articles