我已经尝试阅读此内容,并且可以使len()
函数与除堆栈之外的所有内容一起使用。我尝试了多种不同的想法,并感到它很简单。有谁看到我遇到的问题。我没有任何线索。我会很感谢您的帮助。
class HardwareID():
#empty list created
def __init__(self):
self.items = []
#push for python
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
#implimented for learning
def peek(self):
if not self.is_empty():
return self.items[-1]
def get_stack(self):
return self.items
s = HardwareID()
print ("The stack the right is the top")
s.push("LCD")
s.push("LED")
s.push("Mobile")
s.push("Charger")
s.push("Speaker")
s.push("Mouse")
s.push("Keyboard")
s.push("Laptop")
print (s.get_stack())
print (len(s))
s.pop()
s.pop()
s.pop()
print (s.get_stack())
解决您的问题的简单方法是将以下方法添加到您的类中。
def __len__(self):
return len(self.items)