Reputation: 55
Im having trouble with this fifo-queue program, i've worked out most of the code, which looks like this:
class fifoQueue:
__L = []
def __init__(self):
self.__L = []
def __len__(self):
return len(self.__L)
def empty(self):
if len(q) == 0:
return True
else:
return False
def enqueue(self, e):
self.__L.insert(0, e)
return self.__L
def dequeue(self):
if self.empty():
self.__L = [e]
else:
return self.__L.pop()
def __str__(self):
return "'" + str(self.__L) + "'"
the problem I have is with the __ str __(self) function, what I want it to do is to return my list self.__L with "'" if I call print(str(q)), but if I only call print(q) I want it to return the list. Right now I get the same output for both print(q) and print(str(q)).
(print(str(q)) returns '[31.0]'
print(q) returns '[31.0]'
whereas I would like it to return
str(q) returns '[31.0]' or print(str(q)) returns '[31.0]'
print(q) returns [31.0]
I come from a background in mathematics and this is one of the first languages im learning so I apologize if this is very basic. This is an assignment where I have to only use __ str __ to accomplish this, no additional functions can be created. Any directions are greatly appreciated.
Upvotes: 1
Views: 3882
Reputation: 1002
The __str__ method should be as follows:
def __str__(self):
return str(self.__L) # delegate to built-in function (no concatenation with quote)
Or:
def __str__(self):
return '{self.__L !s}'.format(self.__L) # string formatting
Upvotes: 1