python - 为什么这会给出 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]
当我尝试访问len
main() 中的属性时,它会给出属性错误....
import ADT as ADT
def main():
stack = ADT.Stack()
print (stack)
AttributeError: 'Stack' object has no attribute 'len'
这是怎么回事?我试过 getattr() 也失败了。