2017-07-16 74 views
-2

这是一个Python问题。如何将一个类参数传递给装饰器?

我在一个util文件中编写了一个装饰器,然后我用一些成员函数定义了一个类,我想用装饰器来装饰一个函数,并且装饰器有一个参数来控制代码的运行。当我装饰成员函数,我只想给一个类成员值或类实例值,如何实现呢?

+0

得到使用成员函数的一个小例子,装饰器和装饰器功能本身? – Grimmy

+0

[可以修饰方法或函数的参数的基于Python类装饰器的可能的副本](https://stackoverflow.com/questions/9416947/python-class-based-decorator-with-parameters-that-c​​an-decorate -a法,或-A-FUN) – Kallz

回答

1

不完全知道你是问什么,因为有一个在你的问题没有示例代码,但这里有一个猜测:

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

输出:

in method foo 
doing something with 'baz' control before calling bar() 
in method bar 
相关问题