如何将类的实例作为参数传递给修饰类中定义的实例方法的修饰器?

2024-04-25 23:57:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Python3中实现一个堆栈,对于一些需要检查Stack Empty或Stack Full的方法,我想编写一个decorator,它将负责检查相同的堆栈,并可用于需要这些检查的各种方法。你知道吗

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

你知道吗复制链接: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

Tags: 方法instanceselfexecutereturnstackdefcheck
1条回答
网友
1楼 · 发布于 2024-04-25 23:57:42

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

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,所以您可以使用它。你知道吗

相关问题 更多 >

    热门问题