我已尝试阅读此内容,并且可以使该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.itemss = 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())
2 回答
万千封印
TA贡献1891条经验 获得超3个赞
您可以为您的类实现该__len__方法:HardwareID
def __len__(self):
return len(self.get_stack())
实现此方法将实现所需的行为:
s = HardwareID()
print(len(s)) # 0
s.push("A value")
s.push("B value")
print(len(s)) # 2
s.pop()
print(len(s)) # 1
添加回答
举报
0/150
提交
取消
