为什么这会给出 AttributeError? 在 Python 中访问类属性

问题描述

我有以下堆栈的实现:

class Stack:
    len = 0
    def __init__(self):
        self.items = []
        self.len = 0

    # isEmpty() - returns True if stack is empty and false otherwise
    def isEmpty(self):
        return self.items == []
    # push() - Insert item at the top of the stack
    def push(self,item):
        self.items.append(item)
        self.len = self.len + 1

    # pop() - Remove and return element from top of the stack,# provided it is not empty
    def pop(self):
        return self.items.pop()
        self.len = self.len - 1

    # also kNown as peek() - return top element from stack without removing,#
    def top(self):
        return self.items[len(self.items)-1]

当我尝试访问 main() 中的 len 属性时,它给出了一个属性错误....

import ADT as ADT
def main():
    stack = ADT.Stack()
    print (stack)
AttributeError: 'Stack' object has no attribute 'len'

这是怎么回事?我试过 getattr() 也失败了。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)