Python. Instead of printing actual values from the Stack object it returns an address of that object

Viewed 26

Instead of printing actual values from the Stack object it returns an address of that object.

class Stack: def init(self): self._theItems = list()

def push(self, item):
    self._theItems.append(item)

def pop(self):
    assert not self.is_empty(), "Cannot pop from an empty stack"
    return self._theItems.pop()

def get_top(self):
    assert not self.is_empty(), "Cannot peek at an empty stack"
    return self._theItems[-1]

def is_empty(self):
    return len(self._theItems) == 0

def display(self):
    return self
1 Answers

That is because you have not defined any repr or str method. Please modify the program like shown below:

    def __str__(self):
        return f'The customized stack has values: {self._theItems}'

    def __repr__(self):
        return self.__str__()

    def display(self):
        return self.__repr__()

if __name__ == "__main__":
    customized_stack = Stack()
    customized_stack.init()
    customized_stack.push(10)
    customized_stack.push(20)
    customized_stack.push(30)
    customized_stack.push(40)
    print(customized_stack)

The when you run it, you get:

The customized stack has values: [10, 20, 30, 40]
Related