2013-11-25 61 views
0

我想从我的字典VALUES中获取值。我的程序创建可能的职位组合并获得最后的职位。然后,我想获得价值。除了表示.get_value方法之外,一切运行良好。当我执行这个代码,我得到:从OOP字典中获取值:“AttributeError”

AttributeError的:“组合”对象有没有属性“的get_value”

理论上它应该很容易,但我相信新的面向对象,我看不出这里有什么问题。

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

VALUES = {'A':10, 'B': 50, 'C':-20} 

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 __repr__ (self): 
     return self.x+self.y 

    def get_x(self): 
     return self.x 

    def get_y(self): 
     return self.y 

class 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) 

class Operation1: 
    def __init__(self): 
     self.operation1 = [] 

    def __str__(self): 
     s = str(self.operation1) 
     return s 

    def get_value(self): 
     V = VALUES.get(self) 
     return V 

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

last_value = last_item.get_value() # <---- Here is a problem 

如何获取我的职位价值?值由X值确定 - 这是A,B或C.在字典中,我有一个字母数字值。

回答

1
  1. 要附加的Combination物体进入的Positionxy。当你说choose_last时,它会返回插入xy的最后一个Combination对象。并且您正尝试在Combination对象上调用get_value方法,该对象不具有该方法。这就是为什么你会得到这个错误。

  2. 总是使用新的风格类。

+0

我可以以某种方式使用我的Operation1类获取此值吗?因为以后我想更多地使用这个类? – Kwiaci