【问题标题】:How to return the value of given key in method - dictionary如何在方法中返回给定键的值 - 字典
【发布时间】:2019-09-10 01:59:09
【问题描述】:

我正在尝试编写一个简单的自动售货机。 我有包含项目的 Container 类,而 Items 类包含奖品和金额等信息。 ID 标识项目。每个调用 add item 都会将 ID 加一,因此每个 item 都是唯一的。 我想获得给定ID的奖品。 例如:我添加项目,它的 ID=30,我给出 ID,它返回它的奖品。

我尝试了类似的方法,但它不起作用:

from Item import Item

class Container:
    id = 30

    def __init__(self, objects=None):
        if objects is None:
            objects = {}
        self.objects = objects

    def add_object(self, obj: Item):
        self.objects.update({id: obj})
        Container.id = container.id + 1

    def get_length(self):
        return len(self.objects)

    def find_price_of_given_id(self, id):
        # return self.objects.get(id).get_price()
        pass


Cola = Item(20)
print(Cola.get_amount())
container = Container()
container.add_object(Cola)
print(container.objects.items())

物品类别:

class Item:
    def __init__(self, price,amount=5):
        self.amount = amount
        self.price = price

    def get_price(self):
        return self.price

    def get_amount(self):
        return self.amount

我不知道为什么print(container.objects.items()) 也返回dict_items([(<built-in function id>, <Item.Item object at 0x00000000022C8358>)]),为什么不 ID = 30 + Item 对象

【问题讨论】:

    标签: python dictionary


    【解决方案1】:
    1. id 是内置方法的名称。不要将其用作变量名 - 会导致名称混淆。

    2. 您在容器类中分配了 id,但从未将其返回,以便人们可以使用该 id 查找项目。

    3. 在 python3 中,dict.items 返回一个 dict_items 迭代器,因此您需要对其进行迭代以获取其中的项目。

    class Item:
        def __init__(self, price, amount=5):
            self.amount = amount
            self.price = price
    
        def get_price(self):
            return self.price
    
        def get_amount(self):
            return self.amount
    
        def __str__(self):
            return f"{self.amount} @ {self.price}"
    
    
    class Container:
        item_id = 30
    
        def __init__(self, objects=None):
            if objects is None:
                objects = {}
            self.objects = objects
    
        def add_object(self, obj: Item):
            id_to_assign = Container.item_id
            self.objects.update({id_to_assign: obj})
            Container.item_id = Container.item_id + 1
            return id_to_assign
    
        def get_length(self):
            return len(self.objects)
    
        def find_price_of_given_id(self, item_id):
            return self.objects.get(item_id).get_price()
    
    
    Cola = Item(20)
    print(Cola.get_amount())
    container = Container()
    cola_id = container.add_object(Cola)
    print(container.objects.items())
    print(container.find_price_of_given_id(cola_id))
    

    输出:

    5
    dict_items([(30, <__main__.Item object at 0x104444b00>)])
    20
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 2017-08-16
      • 2013-08-07
      • 1970-01-01
      • 2022-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多