我想在Python3中实现一个Stack,对于某些需要检查Stack Empty或Stack Full的方法,我想编写装饰器来检查它们,并可以用于需要这些检查的各种方法。 / p>
这是我尝试做的(请检查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
答案 0 :(得分:2)
但是,如果您确实需要这样做,请编写代码:
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,因此您可以使用它。