1 回答
TA贡献1813条经验 获得超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 所以你可以使用它。
添加回答
举报