[英]How to correctly inherit class from another file
我有2个档案。 driver.py和stack.py 。 我想将基类stack.py的2个函数继承到driver.py中 ,但实际上在创建类时遇到了问题(运行时遇到属性错误)。 该代码应要求用户输入,直到收到“ end”为止,并且程序应输出所有输入。
请不要理会格式错误,我在代码片段中遇到了包括“导入”行的问题。
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'
这是因为Stack()
实例没有stacker()
方法。
stacker
方法属于您的Test
类。
而不是打字
>>> s = Stack()
>>> s.stacker()
你应该使用
>>> t = Test()
>>> t.stacker()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.