Search code examples
ooppython-3.xstack

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. 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:

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))

Solution

  • What happens is that append method doesn't return anything.

    print [].append(1)
    >>> None
    

    It does its job, but doesn't return anything, that's why you are getting None in variable ok. I think you want to return the _values instead:

    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.