Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用类方法装饰其他类方法?_Python_Decorator - Fatal编程技术网

Python 如何使用类方法装饰其他类方法?

Python 如何使用类方法装饰其他类方法?,python,decorator,Python,Decorator,在设计类时,我发现在类方法中,每次调用类方法时都会重复调用步骤。例如: class Queue(object): def __init__(self): self.connection = Connection() def create(self, name): self.probe = self.connection.plug() self.probe.create(name) self.probe.unplug

在设计类时,我发现在类方法中,每次调用类方法时都会重复调用步骤。例如:

class Queue(object):
    def __init__(self):
        self.connection = Connection()

    def create(self, name):
        self.probe = self.connection.plug()
        self.probe.create(name)
        self.probe.unplug()

    def delete(self, name):
        self.probe = self.connection.plug()
        self.probe.delete(name)
        self.probe.unplug()
还有许多方法需要类似于“插入”和“拔下”探针的步骤。在这种设计中,我们需要在每次执行操作时“插入”和“拔下”探测器

因此,我考虑使用decorator包装这些函数,以减少代码的重复

class Queue(object):
    def __init__(self):
        self.connection = Connection()

    def _with_plug(self, fn):
        def wrapper(*args, **kwargs):
            self.probe = self.connection.plug()
            fn(*args, **kwargs)
            self.probe.unplug()

    @_with_plug        
    def create(self, name):
        self.probe.create(name)

    @_with_plug
    def delete(self, name):
        self.probe.delete(name)

但这一策略并不奏效。在调用方法之前和之后,我如何使用类中的方法来修饰其他方法以执行此类操作?

对我来说似乎有点糊涂:

比如说,文件deco.py

def _with_plug(fn): # decorator takes exactly one argument, the function to wrap
    print("wrapping", fn.__name__)
    def wrapper(self, *args, **kwds):
        print("wrapper called")
        self.probe = [self.connection, ".plug()"]
        fn(self, *args, **kwds)
        self.probe.append(".unplug()")
    return wrapper # decorator must return the wrapped function


class Queue(object):
    def __init__(self):
        self.connection = "Connection()"

    @_with_plug
    def create(self, name):
        self.probe.append("create(name)")

    @_with_plug
    def delete(self, name):
        self.probe.append("delete(name)")
检查:

>>> import deco
wrapping create
wrapping delete
>>> q = deco.Queue()
>>> q.create("name")
wrapper called
>>> q.probe
['Connection()', '.plug()', 'create(name)', '.unplug()']

请注意,decorator函数是在待包装函数的定义时调用的,即在类定义完成之前以及在创建第一个实例之前。因此,您不能以您尝试的方式引用
self

您应该在类主体之外定义decorator函数,并且decorator函数应该返回包装好的函数,以便它工作。比如:

def _with_plug(fn):
    def wrapper(self, *args, **kwargs):
        self.probe = self.connection.plug()
        fn(self, *args, **kwargs)
        self.probe.unplug()
    return wrapper


class Queue(object):
    def __init__(self):
        self.connection = Connection()

    @_with_plug        
    def create(self, name):
        self.probe.create(name)

    @_with_plug
    def delete(self, name):
        self.probe.delete(name)

“但是这个策略不起作用”是什么意思?看起来像是使用一个方法作为装饰器-如代码所示-总是会给出错误,说明参数的数量。我认为我使用decorator的方式是不正确的。您的类decorator方法不是Python意义上的类方法,但必须是。