[英]initializing basic stack, but errors i do not comprehend
i am trying to initialize a basic stack - with push, and pop function. 我正在尝试初始化基本堆栈-具有推入和弹出功能。 the problems comes in while testing.
测试时会出现问题。 you will notice in the code that i have pushed 2 times, so a print of the stack should display
[5,5]
whereas it is displaying None
. 您会在代码中注意到我已推送2次,因此堆栈的打印内容应显示
[5,5]
而显示的是None
。 I could tinker with the code to make it work eventually, but then i will not fully understand the underlying concepts and the error of my ways. 我可以修改代码以使其最终运行,但是那时我将不会完全理解基本概念和我的方式的错误。 so i ask for advice and pointers.
所以我寻求建议和指示。 please check out these codes and tell me what i am doing wrong.
请查看这些代码,然后告诉我我在做什么错。
this is the code with the class with all it's functions, it is named stack_class
: 这是具有所有功能的类的代码,其名称为
stack_class
:
class Stack:
def __init__(self):
self._values = []
print ('Stack initialized...')
return
def push(self, var):
ok = self._values.append(var)
return ok
def pop(self):
self.stack.pop()
def __str__(self):
output = "{0}".format(self.ok)
return output
this is the testing code: 这是测试代码:
from stack_class import Stack
ob_1 = Stack()
ob_1.push(5)
print(ob_1.push(5))
What happens is that append
method doesn't return anything. 发生的事情是
append
方法不返回任何内容。
print [].append(1)
>>> None
It does its job, but doesn't return anything, that's why you are getting None
in variable ok
. 它可以完成工作,但不返回任何内容,这就是为什么变量
ok
None
的原因。 I think you want to return the _values
instead: 我认为您想改为返回
_values
:
def push(self, var):
self._values.append(var)
return self._values
Output: 输出:
Stack initialized...
[5, 5]
Also, it's the first time I read about empty return convention . 另外,这是我第一次了解空返回约定 。 It's not necessary.
这不是必需的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.