Python 从字典中获取值

Python 从字典中获取值,python,class,oop,dictionary,Python,Class,Oop,Dictionary,下面是我正在使用的代码。我的程序创建可能的位置组合并获取最后一个位置。然后,我想根据列表A中的字母和字典值获取该位置的值。当我执行此代码时,我得到: 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 combinat

下面是我正在使用的代码。我的程序创建可能的位置组合并获取最后一个位置。然后,我想根据列表A中的字母和字典值获取该位置的值。当我执行此代码时,我得到:

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()
有人知道如何以最简单的方式更改此代码以使其正常工作吗

该程序的逻辑: 我们有可能的X,Y位置。我们创造了所有可能的组合。然后我们从可能的组合中选择最后一个位置,例如:C3 在此之前,该程序工作正常 现在我想得到位置C3的值。在C3中使用“C”的字典值是3。我想打印这个值(3)

为此,我添加了以下方法:

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

如果我正确理解您的问题,这就是解决方案:

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
返回self.xy.pop()
从列表中返回一个元素。