0

So I'm making my first program in python 3 with operators overloading, and I'm stucked over the add (+) operator.

def __add__(self, newMember):
    if(isinstance(newMember, Queue)):
       tempList=self.myQueue[:] # makes a copy
       tempList.extend(newMember.myQueue)
       return Queue(tempList)

def __str__(self):
    if not self.myQueue:
        string="."
    else:
        string=""
        for x in self.myQueue:
            string=string+str(x)
            if(x<len(self.myQueue)):
                string=string+", "
            else:
                string=string+"."
    return string

basically I'm making a Queue class (I know there's already such one exists), then connecting two Queue objects by typing c=c1+c2. But when I print (c), it messed up the "," and the ".". Can't get what's wrong. Any help?

2
  • Shouldn't you do tempList = Queue(self.myQueue) or something like that? I don't know much about Python but if you just assign self.myQueue to tempList then maybe tempList refers to the same object as self.myQueue... Commented Apr 21, 2012 at 13:52
  • I edited my question. I really did reffered to the same object, so I added [:]. I don't want tempList to be a Queue type but a List type so I can return Queue(list) Commented Apr 21, 2012 at 14:04

2 Answers 2

1

To answer your second question (which should probably be a separate question on SO, rather than editing this one):

if(x<len(self.myQueue)): is checking whether the value of a string is less than an integer length of a list. This doesn't make any sense, and will always be False.

You could rewrite the entire method as:

def __str__(self):
    return ', '.join(str(x) for x in self.myQueue) + '.'
Sign up to request clarification or add additional context in comments.

Comments

0

in your code, you set tempList to self.myQueue, then modify it. This changes both Queues. you want to copy myQueue, not share the reference.

with tmplist = queue, both variables point to the same Object. Maybe this will help to understand:

>>> queue = []
>>> tmplist = queue
>>> tmplist.append(1)
>>> tmplist
[1]
>>> queue
[1]
>>> tmplist = queue[:] #make a copy
>>> tmplist.append(1)
>>> tmplist
[1, 1]
>>> queue
[1]

1 Comment

Thanks ! Now c1 really doens't change. But i still can't print perfectly, it keep messing up "," and ".". I edited the question adding my str code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.