2013-11-21 119 views
2

我嘗試編寫一個程序,它將生成給定範圍的X和Y中所有可能的位置組合。例如:[A1,A2,A3,B1,...] 由於我是OOP的新手,我在打印這些值時遇到了一些問題。下面是我的代碼:從對象列表中獲取價值

X = ['A','B','C'] 
Y = ['1','2','3'] 

class Combination: 
    def __init__(self,x,y): 
     if (x in X) and (y in Y): 
      self.x = x 
      self.y = y 
     else: 
      print "WRONG!!" 

    def __str__ (self): 
     return x+y 

class Position: 
    def __init__(self): 
     self.xy = [] 
     for i in X: 
      for j in Y: 
       self.xy.append(Combination(i,j)) 
    def __str__(self): 
     return "List contains: " + str(self.xy) 

P1 = Position() 
print P1 

我的結果是:

List contains: [<__main__.Combination object>, <__main__.Combination object>,.... 

正如我所說,我希望看到這樣的事情: 〔A1,A2,A3,B1,...] 如果我改變路線:

self.xy.append(Combination(i,j)) 

到:

self.xy.append(i,j) 

它工作正常,但我想在那裏使用類組合。

有誰知道該怎麼做?這裏有什麼問題?

回答

3

Combinations類,你需要定義__repr__方法,而不是__str__這樣

def __repr__ (self): 
    return self.x+self.y 

這種變化,輸出

List contains: [A1, A2, A3, B1, B2, B3, C1, C2, C3] 
+0

謝謝!它工作:)我是OOP的新手,我不知道__repr__只有__str__。你真的救了我,因爲我花了很多時間去想出其他方法。 – Kwiaci

+0

@Kwiaci歡迎您:)請考慮接受此答案,如果它可以幫助您http://meta.stackexchange.com/a/5235/235416 – thefourtheye

0

你的組合__str__方法需要改進。首先,我懷疑它應該是__repr__,其次它需要self.x + self.y

+0

謝謝!有用 :) – Kwiaci