【问题标题】:How to pass instance of a class as a parameter to a decorator decorating an instance method defined in the class?如何将类的实例作为参数传递给装饰类中定义的实例方法的装饰器?
【发布时间】:2019-05-24 12:31:44
【问题描述】:

我想在 Python3 中实现一个 Stack,对于一些需要检查 Stack Empty 或 Stack Full 的方法,我想编写装饰器来检查相同的内容,并可用于需要这些检查的各种方法。

这是我尝试做的(请检查push和pop方法的实现):

repl.it 链接:https://repl.it/@Ishitva/Stack

class StackFullException(Exception):
    pass

class StackEmptyException(Exception):
    pass

def checkStackFull(instance):
    def check(func):
        def execute(*args, **kwargs):
            if len(instance.items) <= instance.limit:
                return func(*args, **kwargs)
            raise StackFullException

        return execute
    return check

def checkStackEmpty(instance):
    def check(func):
        def execute(*args, **kwargs):
            if len(instance.items) > -1:
                return func(*args, **kwargs)
            raise StackEmptyException

        return execute
    return check


class Stack():

    def __init__(self, limit=10):
        self.items = []
        self.limit = limit

    @checkStackFull(self)
    def push(item):
        self.items.append(item)
        return item

    @checkStackEmpty(self)
    def pop():
        return self.items.pop()

    def getSize():
        return len(self.items)

这给了我以下例外:

Traceback (most recent call last):
  File "main.py", line 28, in <module>
    class Stack():
  File "main.py", line 34, in Stack
    @checkStackFull(self)
NameError: name 'self' is not defined

【问题讨论】:

  • 在没有装饰器的情况下,只是从推送和弹出中引发异常,这使问题过于复杂。
  • 我对装饰器不是很熟悉,但这看起来很接近你想要做的:stackoverflow.com/questions/11731136/…

标签: python python-3.x stack python-decorators


【解决方案1】:

但如果你真的需要这样做,那么代码:

class StackFullException(Exception):
    pass

class StackEmptyException(Exception):
    pass


def checkStackFull(func):
    def execute(self, *args, **kwargs):
        if len(self.items) <= self.limit:
            return func(self, *args, **kwargs)
        raise StackFullException()

    return execute


def checkStackEmpty(func):
    def execute(self, *args, **kwargs):
        if len(self.items):
            return func(self, *args, **kwargs)
        raise StackEmptyException()
    return execute


class Stack():
    def __init__(self, limit=10):
        self.items = []
        self.limit = limit

    @checkStackFull
    def push(self, item):
        self.items.append(item)
        return item

    @checkStackEmpty
    def pop(self):
        return self.items.pop()

    def getSize(self):
        return len(self.items)

顺便说一句,从空列表中弹出会引发 IndexError,所以你可以使用它。

【讨论】:

  • 我想建议:def execute(self, *args, **kwargs): ...
猜你喜欢
  • 2017-11-12
  • 2013-07-05
  • 2019-02-03
相关资源
最近更新 更多