【问题标题】:attritbute error : ArrayStack object has no attribute len()属性错误:ArrayStack 对象没有属性 len()
【发布时间】:2020-01-30 13:51:37
【问题描述】:

这是代码:

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)

错误信息

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

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您的 len 定义中有错字。它应该是__len__。 我注意到了第二个问题。你应该大写“空”加注。

【讨论】:

  • 不明白你的意思,请解释一下!
  • 正如 Rushikesh Sabde 所回答的,您有一个错字。第二个问题与 raise empty('Stack is Empty') 相关。它必须是空的('堆栈是空的')。您的对象不是“空”而是“空”。
【解决方案2】:

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

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

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

【讨论】:

  • 请将解决方案标记为已接受,这将有助于我的声誉。
猜你喜欢
  • 1970-01-01
  • 2017-05-13
  • 2014-05-14
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
  • 2020-03-13
  • 2021-12-10
相关资源
最近更新 更多