我试图使用Python通过数组实现Stack。这是我的密码。
class Stack:
def init(self,top,size):
self.size = 4
self.top = []
def isEmpty(self):
if len(self.top) == 0:
return True
else:
return False
def length(self):
return len(self.top)
def peek(self):
if self.Empty() == True :
print("Cannot peek at an empty Stack")
else:
return self.size[len(self.top)]
def pop(self):
if self.isEmpty():
print("Cannot peek at an empty Stack")
else:
value = self.size[len(self.top)-1]
del self.top[len(self.data) - 1]
return value
def push(self, item):
if len(self.top) >= self.size:
print("Cannot push. Stack is full")
else:
self.top.append(item)
s = Stack()
每当我尝试使用推、弹出等操作时。。我收到一个错误,说"Stack对象没有属性top"。
您需要调用init()
方法__init__()
。
此外,您应该根据以下内容从object
继承:所有Python类都应该扩展对象吗?例如:
class Stack(object):
def __init__(self,top,size):
# ...
此外,我不明白为什么你有top
和size
的自变量,却用[]
和4
填充它们。您可以在实例化时传入size
,默认情况下top
是一个列表,例如:
class Stack(object):
def __init__(self,size):
self.size = size
self.top = []