-1

I have to print elements in a stack using classes and all:

class Stack:

    def __init__(self):
        self.stack = []

    def push(self,element):
        self.stack.append(element)

    def pop(self):
        return self.stack.pop()

def st(n):

    s = Stack()
    for i in range(n,0,-1):
        s.push(i)

    #this is updated version now I want to print outside of the loop and 
    #it gives me this error : __main__.Stack instance at 0x7fe40d261710> 
    print s
if __name__ == '__main__':

   st(4)

for some reason instead of printing [4,3,2,1] it print None

pokolo
  • 13
  • 1
  • 1
  • 3
  • You should try to format your code properly and explain what you are trying to achieve and what you have tried, etc... Please refer to:http://stackoverflow.com/help/how-to-ask – GSalazar Oct 02 '15 at 22:19
  • since your push method returns None you see it print None ... – Joran Beasley Oct 02 '15 at 22:22

4 Answers4

1

Your class does not define __str__ or __repr__ method, so print uses the default representation. If you want instances of Stack to be printed as lists, add the following definition to your class:

def __str__(self):
    return str(self.stack)
Alexander Belopolsky
  • 2,228
  • 10
  • 26
1

Stask class using built-ins

Using lists as stack https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index

If you have to provide custom interface for adding elements in stack you can add single method like this:

class Stack(list):
    def push(self, *args, **kwargs):
        self.append(*args, **kwargs)

Printing objects

How print function behave?

Lets look at documentation about print function https://docs.python.org/3/library/functions.html#print

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.

What str() function really does?

If neither encoding nor errors is given, str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object).

This means that you Stack have to support __str__() method, and if it has no such __repr__() will be used.

Look at repr(object) docs if you didn't believe my words https://docs.python.org/3/library/functions.html#repr

A class can control what this function returns for its instances by defining a repr() method.

Also read this answers, which describe my thoughts in different manner:

Summary

class Stack(list):
    """
    Implaments stack interface to access data by inheriting buil-in list
    object.

    Note: all parent methods will be accessable in stack instance.
    """
    def push(self, *args, **kwargs):
        """
        Delegate behaviour to parrent class.
        """
        self.append(*args, **kwargs)

    def __str__(self):
        """
        Because of using list as parent class for stack, our last element will
        be first for stack, according to FIFO principle. So, if we will use
        parent's implementation of str(), we will get reversed order of
        elements.
        """
        #: You can reverse elements and use supper `__str__` method, or 
        #: implement it's behavior by yourself.
        #: I choose to add 'stack' in the begging in order to differ list and
        #: stack instances.
        return 'stack [{}]'.format(', '.join(reversed(self)))


def example_of_usage():
    #: Here we just using parent's list initialization functionality to init
    #: stack from iterable (in our case - list).
    s = Stack(['last', 'first'])
    #: output> stack ['fist', 'last']
    print(s)
    s.push('very first')
    #: output> stack ['very first', 'fist', 'last']
    print(s)
Community
  • 1
  • 1
outoftime
  • 715
  • 7
  • 21
0
print s.push(i)

See the line, s.push() append the value and returns None. So you end up printing None

Your pop() works, because unlike append(), it returns a value.

So, change the function definition like that:

def push(self,element):
    self.stack.append(element)
    return self.stack 
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
0
return "".join(self.stack_objects)
gmdev
  • 2,725
  • 2
  • 13
  • 28
Big Mac
  • 17
  • 4