简体   繁体   English

初始化基本堆栈,但是我不理解错误

[英]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.

相关问题 如何在Forth中创建该类的基本类和实例? - How do I create a basic class and instance of that class in Forth? 在构建对象堆栈时如何解决转换错误? - How do i solve a conversion error while building a stack of objects? 如何在Visual Basic 2012中创建隐藏登录密码的编码(OOP方法) - how do i create a coding to hide login password in visual basic 2012 (OOP method) 如何在基本 Ruby 中跟踪自动实例化的未分配对象? - How do I keep track of automatically instanced unassigned objects in basic Ruby? 我在初始化MATLAB类时遇到了麻烦 - I'm having trouble initializing a MATLAB class AS3,基本的OOP,我猜呢? - AS3, basic OOP, I guess? 当我在两个类之间使用继承时,变量正在初始化 - The variables are initializing when I'm using inheritance between two classes 如何在VBA中初始化对象的属性的帮助下初始化对象 - How Can I Initialize an object with help of properties of initializing object in VBA 我应该如何处理OOP中的基本功能? - How should I handle basic functions in OOP? 我如何解决这些错误:必须调用对非静态成员函数的引用,并且在静态成员函数中无效使用成员“mat”? - How do i fix these errors : reference to non-static member function must be called and invalid use of member 'mat' in static member function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM