gpt4 book ai didi

python - 属性错误: ArrayStack object has no attribute len()

转载 作者:行者123 更新时间:2023-12-01 07:11:45 32 4
gpt4 key购买 nike

这是代码:

class Empty(Exception):
pass

class ArrayStack:
def __init__(self):
self._data = []

def __len(self):
return len(self._data)

def is_empty(self):
return len(self._data)==0

def push(self, e):
self._data.append(e)

def pop(self):
if self.is_empty():
raise empty('Stack is Empty')
return self._data.pop()

def top(self):
if self.is_empty():
raise empty('Stack is Empty')
return self._data[-1]

s= ArrayStack()
s.push(10)
s.push(20)
print('Stack: ', s._data)
**print('Length: ', len(s)) #this line is throwing the problem**
print('Is-Empty: ', s.is_empty())
print('Popped: ', s.pop())
print('Stack: ', s._data)

error message

回溯(最近一次调用最后一次): 文件“main.py”,第 31 行,位于 print('长度:', s.__len())AttributeError:“ArrayStack”对象没有属性“__len”

最佳答案

在您的 ArrayStack 类中你的方法 __len() 是拼写错误。

你的方法应该是len(),因为它是一个神奇的方法。

    def __len__(self):
return len(self._data)

关于python - 属性错误: ArrayStack object has no attribute len(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58181939/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com