使用类访问信息

时间:2016-04-17 21:31:25

标签: python class python-3.x

我正在编写一个以代码形式接收输入并返回字符串的函数。

class Item(object):
    def __init__(self, code, name, stock, price):
        self.code = code
        self.name = name
        self.stock = stock
        self.price = price

beer = Item(124, "beer", 200, 12.90)

print(beer.code)

有没有办法得到这个名字"啤酒"从它的代码,124。就像你可以用字典? dict = {124 : "beer"}

2 个答案:

答案 0 :(得分:0)

假设您首先创建了一个项目列表,例如

items = []
items.append(Item(124, "beer", 200, 12.90)
items.append(Item(125, "diapers", 100, 5.90)

然后,您可以使用列表推导来查找具有给定代码的项目,例如

beer = [item for item in items if item.code==124][0]

这假设您可以保证只有一个代码为124的项目。您甚至可以将其包装在一个函数中:

def find_item(code):
   return [item for item in items if item.code==124][0]

答案 1 :(得分:0)

您可以创建一个Inventory类并执行此操作:

class Item(object):
    def __init__(self, code, name, stock, price):
        self.code = code
        self.name = name
        self.stock = stock
        self.price = price

    def __repr__(self):
        return '{}: {} - {} - {}'.format(self.code, self.name, self.stock, self.price)


class Inventory(object):
    _inventory = {}

    def find(self, code):
        return self._inventory.get(code)

    def add_item(self, code, name, stock, price):
        if code in self._inventory:
            raise KeyError('item with this code already present')
        self._inventory[code] = Item(code, name, stock, price)


inventory = Inventory()
inventory.add_item(124, "beer", 200, 12.90)
inventory.add_item(125, "another beer", 400, 8.10)

search = inventory.find(124)
print search
print search.name

输出:

124: beer - 200 - 12.9
beer