Home > Back-end >  Why __str__(self) doesn't work when calling the print() function?
Why __str__(self) doesn't work when calling the print() function?

Time:07-01

I'm diving into OOP and learning magic (or dunder) techniques. Python 3.8.8.

I created class FreqStack() with a pop() method that removes the most frequent elements and returns an updated stack.

class FreqStack():

def __init__(self, lst:list = None):
    if lst is None:
        self.stack = []
    else:
        self.stack = lst[::-1]

def push(self, el: int):
    self.stack.insert(0, el)
    return self.stack

def pop(self):
    if len(self.stack) != 0:
        hash_map = {}
        for el in self.stack:
            hash_map[el] = hash_map.get(el, 0)   1
        most_freq_el = max(hash_map, key=hash_map.get)

        while most_freq_el in self.stack: 
            self.stack.remove(most_freq_el)
        
        return self.stack 
    else:
        return 'Stack is empty!'
    
def __str__(self):
    return '\n|\n'.join(str(el) for el in self.stack)

I also added the dunder method str(), which, as far as I understand correctly, must return a custom string when calling the print() function. However, the print() function in the example below, instead of returning a string, returns a list.

lst = [1, 1, 1, 5, 5, 5, 3, 3, 3, 7, 7, 9]
freq_stack = FreqStack(lst)

for i in range(6):
    print(freq_stack.pop())

Output:
[9, 7, 7, 5, 5, 5, 1, 1, 1]
[9, 7, 7, 1, 1, 1]
[9, 7, 7]
[9]
[]
Stack is empty!

I googled everything related to this problem, and couldn't solve it. What am I doing wrong?

CodePudding user response:

You are printing the return value of pop, not the freq_stack itself. The __str__ method is for the freq_stack object, so you may try something like:

freq_stack.pop()
print(freq_stack)
  • Related