-2

It is a Python problem.

I have write a decorator at a util file and then I defined a class with some member functions, one of the function I want to decorate with the decorator, and the decorator have a parameter to control the code running. When I decorate the member function, I just want to given a class member value or a class instance value, how to implements that?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Got a minimal example of a member function using the decorator and the decorator function itself? – Grimmy Jul 16 '17 at 15:10
  • Possible duplicate of [Python Class Based Decorator with parameters that can decorate a method or a function](https://stackoverflow.com/questions/9416947/python-class-based-decorator-with-parameters-that-can-decorate-a-method-or-a-fun) – Kallz Jul 16 '17 at 15:10

1 Answers1

1

Not exactly sure what you're asking since there's no sample code in your question, but here's a guess:

import functools
#from utilities import my_decorator  # in-lined below for simplicity

def my_decorator(control):
    def wrapper(function):
        " Do something with function or before and after it returns. """

        @functools.wraps(function)
        def wrapped(*args, **kwargs):
            print('doing something with {!r} control before calling {}()'.format(
                    control, function.__name__))
            return function(*args, **kwargs)

        return wrapped

    return wrapper


class Test(object):
    def foo(self):
        print('in method foo')

    @my_decorator('baz')
    def bar(self):
        print('in method bar')


test = Test()
test.foo()
test.bar()

Output:

in method foo
doing something with 'baz' control before calling bar()
in method bar
martineau
  • 119,623
  • 25
  • 170
  • 301