Object-oriented python attributes

Hi. I am working on the practice questions for object-oriented python and am currently stuck on this question: https://app.dataquest.io/m/1000352/object-oriented-python-practice-problems/6/supermarket-queue

The question says there are multiple ways of doing it and mine is very different from the model answer.

here is my code:

class SupermarketQueue():
    def __init__(self):
        self.queue = []
       
    def add_at_back(self, element):
        self.queue.insert(0, element)
        return self.queue
    
    def remove_from_front(self):
        self.queue.pop(-1)
        return self.queue
    
    
    def __len__(self):
        return len(self.queue)

queue = SupermarketQueue()
queue.add_at_back('Alice')
queue.add_at_back('Bob')
print(len(queue))
print(queue)
print(queue.remove_from_front())

This is the output that I get:

2
<__main__.SupermarketQueue object at 0x7f7077583e80>
['Bob']

Why does the add_at_back attribute not work?
Furthermore, the question says I should include a str method and len method. I don’t understand why this needs to be done when a) there is a built-in len() and b) surely the output will automatically be a list since self.queue is saved as an empty list? Is this code totally incorrect or can I make some minor adjustments to get it to work? As I say, the model answer is extremely different so I may be miles off!

I hope this makes sense - thanks in advance!

I’ve realised that I misread the question! here is my new code, which seems to work. I’d still appreciate if anyone has any tips or ideas to improve it. Thanks :slight_smile:

class SupermarketQueue():
    def __init__(self):
        self.queue = []
       
    def add_at_back(self, element):
        if not element in self.queue:
            self.queue.insert(0, element)
        return self.queue
    
    def remove_from_front(self):
        return self.queue.pop(-1)
        
        
    
    def __str__(self):
        return '{}'.format(self.queue)
    
    
    def __len__(self):
        return len(self.queue)

queue = SupermarketQueue()
queue.add_at_back('Alice')
queue.add_at_back('Bob')

print(len(queue))
print(queue)
print(queue.remove_from_front())
1 Like

I believe your solution is more improved since the solution provided can be more complex to beginners. Kudos!!

1 Like