2013-11-25 4 views
0

아래 코드는 내가 작업하고있는 코드입니다. 내 프로그램은 가능한 위치의 조합을 만들고 마지막 위치를 얻습니다. 그런 다음 목록 A의 문자와 사전 VALUES를 기반으로 해당 위치의 값을 가져 오려고합니다. 이 코드를 실행하면 내가 얻을 :사전에서 값 가져 오기

AttributeError을 '조합'개체가

X = ['A','B','C'] 
Y = ['1','2','3'] 
VALUES_FOR_X = {'A':1, 'B': 2, 'C':3} 

class Combination: # Creates a list of possible position combinations 
    def __init__(self,x,y): 
     if (x in X) and (y in Y): 
      self.x = x 
      self.y = y 
     else: 
      print "WRONG!!" 

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

class Position:  # Makes operation on the chosen position 
    def __init__(self): 
     self.xy = [] 
     for i in X: 
      for j in Y: 
       self.xy.append(Combination(i,j)) 

    def choose_last(self): 
     return self.xy.pop() 

    def get_value(self): 
     return self.VALUES_FOR_X() 

    def __str__(self): 
     return "List contains: " + str(self.xy) 

pos = Position() 
print pos 
last_item = pos.choose_last() 
print "Last item is:", last_item 
print last_item.get_value() 

사람은 간단한 방법이 코드를 변경하는 것이 작동하는 방법을 알고 있는가 'get_value을'어떤 속성이 없다?

이 프로그램의 논리는 다음과 같습니다. 가능한 X, Y 위치가 있습니다. 가능한 모든 조합을 만듭니다. 그런 다음 가능한 조합 (예 : C3 )에서 마지막 위치를 선택했습니다. 여기까지 프로그램이 완벽하게 작동합니다. 이제 위치 C3 값을 가져 오려고합니다. C3에서 'C'에 대한 사전 값 사용은 3입니다.이 값 (3)을 인쇄하고 싶습니다. 내가 제대로이 솔루션 인 문제 이해한다면

def get_value(self): 
    return self.VALUES_FOR_X() 
+0

가 '자기를 반환

이 내가 방법을 추가 할합니다. xy.pop()'은리스트에서 하나의 원소를 반환한다. –

답변

1

:

X = ['A','B','C'] 
Y = ['1','2','3'] 
VALUES_FOR_X = {'A':1, 'B': 2, 'C':3} 

class Combination: # Creates a list of possible position combinations 
    def __init__(self,x,y): 
     if (x in X) and (y in Y): 
      self.x = x 
      self.y = y 
     else: 
      print "WRONG!!" 

    def get_value(self): 
     return VALUES_FOR_X[self.x] 

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

class Position:  # Makes operation on the chosen position 
    def __init__(self): 
     self.xy = [] 
     for i in X: 
      for j in Y: 
       self.xy.append(Combination(i,j)) 

    def choose_last(self): 
     return self.xy.pop() 



    def __str__(self): 
     return "List contains: " + str(self.xy) 

pos = Position() 
print pos 
last_item = pos.choose_last() 
print "Last item is:", last_item 
print last_item.get_value() 

내 출력은 다음과 같습니다

>>> List contains: [A1, A2, A3, B1, B2, B3, C1, C2, C3] 
>>> Last item is: C3 
>>> 3 
+0

Ahh ok, 내 수정 된 답변보기. 가능한 해결책을 찾으십시오. – Mailerdaimon

+0

감사합니다. – Kwiaci