0

I have this training exercise where I need to find the problems in this program. I can't find them and python tutor does not allow me to see the object created. It just says incomplete object. The program should create a kind of queue for strings. What is wrong with the code?

class A():
"""Eine Art Warteschlange für Strings"""

    def __init__(self, wait = [], now = ""):
        self.wait = wait
        self.now = now

    def new_string(self, x):
        """Fügt einen String zur Warteschlange hinzu"""
        self.wait.append(str(x))

    def next_string(self):
        """Holt den nächsten String aus der Warteschlange, speichert ihn als aktuellen String"""
        self.now = self.wait[0]
        self.wait.pop(0)

    def top(self):
        """Gibt den aktuellen String zurück"""
        return self.now

    def __str__(self):
        return self.top
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135

1 Answers1

1

Here are the few bugs I came across in your class.(There may be more):

  • Under indentation of the class docs.
    Fix: Indent it by 4 spaces to the right.

  • The __str__ magic method doesn't return a string.
    Fix: Replace self.top with self.top(). You would want to return the value returned by the method top.

  • Not updating the attribute now whenever new_string is added.
    Since, you are using the object's now attribute in __str__, it is advisable to update it whenever an empty object is initialised using new_string method. There are several ways to do. I would suggest you fix this as you see fit.

Example:

In []: a = A()
In []: a.new_string('foo')
In []: print(a)

In []: a.now
Out[]: ''
In []: a.wait
Out[]: ['foo']
Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71