我有2个文件。 driver.py 和 stack.py 。我想将基类 stack.py 的2个函数继承到 driver.py ,但是我遇到了实际创建类的问题(遇到属性)跑步时的错误)。该代码应该要求用户输入直到'结束'收到并且程序应该输出所有输入。
请忽略格式错误,我遇到的问题包括' import'片段中的行。
class Stack:
def __init__(self):
'''A new empty stack'''
self.items = []
def push(self, o):
'''Make o the new top item in this Stack.'''
self.items.append(o)
def pop(self):
'''Remove and return the top item.'''
return self.items.pop()
def peek(self):
'''Return the top item.'''
return self.items[-1]
def isEmpty(self):
'''Return whether this stack is empty.'''
return self.items == []
def size(self):
'''Return the number of items in this stack.'''
return len(self.items)
class UpStack:
def __init__(self):
'''A new empty stack'''
self.stack = []
def push(self, o):
'''Make o the new top item in this Stack.'''
self.stack.insert(0, o)
def pop(self):
'''Remove and return the top item.'''
return self.stack.pop(0)
def peek(self):
'''Return the top item.'''
return self.stack[0]
def isEmpty(self):
'''Return whether this stack is empty.'''
return self.stack == []
def size(self):
'''Return the number of items in this stack.'''
return len(self.stack)

from stack import *
if __name__ == '__main__':
#-----------------------------------Stack Code-----------------------------------
s = Stack()
s.push('Hello')
print(s.pop())
data = ""
while data.lower() != 'end':
data = input("Enter Command: ")
if data.lower() != 'end':
s.push(data)
while not s.isEmpty():
print(s.pop())
#-----------------------------------UpStack Code-----------------------------------
u = UpStack()
u.push('Hello')
print(u.pop())
data = ""
while data.lower() != 'end':
data = input("Enter Command: ")
if data.lower() != 'end':
u.push(data)
while not u.isEmpty():
print(u.pop())

from stack import *
class Test:
#-----------------------------------Stack Code-----------------------------------
def stacker(self):
s = Stack()
s.push('Hello')
print(s.pop())
data = ""
while data.lower() != 'end'
data = input("Enter Command: ")
if data.lower() != 'end':
s.push(data)
while not s.is_empty():
print(s.pop())
#-----------------------------------UpStack Code-----------------------------------
def upstacker(self):
u = UpStack()
u.push('Hello')
print(u.pop())
data = ""
while data.lower() != 'end':
data = input("Enter Command: ")
if data.lower() != 'end':
u.push(data)
while not u.is_empty():
print(u.pop())

由于在实际运行代码时我没有看到任何内容,因此我创建了一个实例,这就是我得到的。
>>> s = Stack()
>>> s
<stack.Stack object at 0x103bb3a58>
>>> s.push(2)
>>> s.stacker()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
s.stacker()
AttributeError: 'Stack' object has no attribute 'stacker'
答案 0 :(得分:1)
这是因为Stack()
实例没有stacker()
方法。
stacker
方法属于您的Test
类。
而不是输入
>>> s = Stack()
>>> s.stacker()
你应该使用
>>> t = Test()
>>> t.stacker()