2012-04-21 53 views
0

所以我在Python 3与运营商超载使我的第一个程序,我stucked在添加(+)运算符。__add__方法在Python 3

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 

基本上我正在做Queue类(I已经知道有这样一个存在),然后通过键入C = C1 + C2连接两个队列对象。但是当我打印(c)时,它弄乱了“,”和“。”。不能得到什么错误。 有什么帮助吗?

+0

你不应该做'tempList =队列(self.myQueue)'或类似的东西?我不太了解Python,但是如果你只是将'self.myQueue'赋值给'tempList',那么'tempList'指的是与'self.myQueue'相同的对象... – dreamlax 2012-04-21 13:52:14

+0

我编辑了我的问题。我真的对同一个对象有所反应,所以我添加了[:]。我不希望tempList是一个队列类型,但一个列表类型,所以我可以返回队列(列表) – Jjang 2012-04-21 14:04:01

+0

为什么这标记为[C++]? – geoffspear 2012-04-21 14:07:27

回答

0

在您的代码中,您将tempList设置为self.myQueue,然后对其进行修改。 这个变化都是队列。你想复制myQueue,不能共享参考。

与tmplist =队列,两个变量指向相同对象。 也许这将有助于了解:

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

谢谢!现在c1真的不会改变。但是我仍然无法完美打印,它一直在搞乱“,”和“。”。我编辑了添加我的__str__代码的问题 – Jjang 2012-04-21 13:59:48

1

要回答你的第二个问题(这大概应该是一个单独的问题上SO,而不是编辑此一):

if(x<len(self.myQueue)):是检查是否a的值字符串小于列表的整数长度。这没有任何意义,并将永远是假的。

你可以重写的整个方法:

def __str__(self): 
    return ', '.join(str(x) for x in self.myQueue) + '.'