如何在Python的OOP中从字典中获取值

70 阅读2分钟

假设我们有一个字典 VALUES,其中包含一些关键值对。我们想创建一个名为 Combination 的类,它可以存储两个值 x 和 y,并通过 get_x 和 get_y 方法获取这些值。我们还创建一个名为 Position 的类,它可以存储多个 Combination 对象,并通过 choose_last 方法获取最后一个 Combination 对象。最后,我们创建一个名为 Operation1 的类,它可以存储多个值,并通过 get_value 方法获取最后一个值的数值。

huake2_00020_.png 当我们尝试运行以下代码时,会遇到一个错误:

AttributeError: 'Combination' object has no attribute 'get_value'

这是因为 get_value 方法不是 Combination 类的一个方法。

2、解决方案

为了解决这个问题,我们可以将 get_value 方法添加到 Combination 类中。修改后的代码如下:

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

    def get_value(self):
        V = VALUES.get(self.x)
        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

现在,我们可以通过 last_item.get_value() 方法获取最后一个 Combination 对象的数值。

此外,还可以通过修改Position类的choose_last方法,使其直接返回Combination对象的x值,这样就可以避免在Combination类中定义get_value方法。修改后的代码如下:

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().x

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

修改后的代码中,choose_last方法直接返回Combination对象的x值,而不再返回Combination对象本身。这样,就可以通过pos.choose_last()直接获取最后一个Combination对象的x值,从而避免在Combination类中定义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().x

    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

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

last_value = VALUES.get(last_item)  # get value from dictionary directly

运行新的代码,就不会出现错误。