我想在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
最佳答案
但是如果你确实需要这样做,那么编码:
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,所以你可以使用它。
关于python - 如何将类的实例作为参数传递给装饰类中定义的实例方法的装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53928764/