我想在 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
慕姐8265434
相关分类