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

我想在 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


偶然的你
浏览 238回答 1
1回答

慕姐8265434

但如果你真的需要这样做,那么代码:class StackFullException(Exception):&nbsp; &nbsp; passclass StackEmptyException(Exception):&nbsp; &nbsp; passdef checkStackFull(func):&nbsp; &nbsp; def execute(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; if len(self.items) <= self.limit:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return func(self, *args, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; raise StackFullException()&nbsp; &nbsp; return executedef checkStackEmpty(func):&nbsp; &nbsp; def execute(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; if len(self.items):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return func(self, *args, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; raise StackEmptyException()&nbsp; &nbsp; return executeclass Stack():&nbsp; &nbsp; def __init__(self, limit=10):&nbsp; &nbsp; &nbsp; &nbsp; self.items = []&nbsp; &nbsp; &nbsp; &nbsp; self.limit = limit&nbsp; &nbsp; @checkStackFull&nbsp; &nbsp; def push(self, item):&nbsp; &nbsp; &nbsp; &nbsp; self.items.append(item)&nbsp; &nbsp; &nbsp; &nbsp; return item&nbsp; &nbsp; @checkStackEmpty&nbsp; &nbsp; def pop(self):&nbsp; &nbsp; &nbsp; &nbsp; return self.items.pop()&nbsp; &nbsp; def getSize(self):&nbsp; &nbsp; &nbsp; &nbsp; return len(self.items)顺便说一下,从空列表中弹出无论如何都会引发 IndexError 所以你可以使用它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python