0

到目前为止,这是我的代码:

class Compound(Item):

    def __init__(self, itemID, name, products, itemlist):
        Item.__init__(self,itemID,name)
        self._products = products
        self._items_list = itemlist


    def get_cost(self):
        return self._cost

    def get_items_list(self):
        return self._items_list

    def get_items_str(self):
        return "".format(self._itemID, self._name)

    def set_items(self, itemlist):
        self._itemlist= itemlist

    def get_depend(self):
        allitems = []
        for a in self._set_items:
            allitems.append(n[0])
            return allitems

    def __repr__(self):
        return "{0}, {1}, {2}".format(self._itemID, self._name, self._products, self._items_list)

    def __str__(self):
        return '{0}     {1}                            {2}'.format(self._itemID, self._name, self._products, self._item_list)

class Products():
   def __init__(self):
        self._products = {}

   def get_item(self, itemID):
        return self._products.get(itemID)

    def add_item(self, itemID, product):
        self._products[itemID] = product

    def remove_item(self, itemID, product):
        if item in products:
            self._products.remove(item)
            return True
        return False

    def delete_all(self):
        self._products.clear()

    def get_keys(self):
        return self._products.keys()

    def check_depend(self, item):
        for i in self._products:
            depend = self._products(i).get_depend()
            if item in depend:
                return True
            return False

当我运行以下代码时:

products.add_item('CWH111', Compound('CWH111', 'Mountain Bike Built Wheel', products, [('TR202', 1), ('TU227', 1), ('WH239', 1)]))
products.get_item('CWH111')

我想得到

CWH111, Mountain Bike Built Wheel, TR202:1,TU227:1,WH239:1

但相反,我得到的只是

CWH111, Mountain Bike Built Wheel, <____main____.Products instance at 0x0000000002727588>

我尝试了很多不同的东西;有人可以告诉我我做错了什么吗?

4

1 回答 1

2

您没有在self._items_list此处使用指定字符串格式化程序的参数:

return "{0}, {1}, {2}".format(self._itemID, self._name, self._products, self._items_list)

那里只有 3 个插槽({0}{1}{2},但传入4 个参数。以下已经更好了:

return "{0}, {1}, {2}".format(self._itemID, self._name, self._items_list)

即使那不会完全打印您想要的内容。

你想格式化self._items_list更多:

il = ','.join(['{0}:{1}'.format(*item) for item in self._items_list])
return "{0}, {1}, {2}".format(self._itemID, self._name, il)
于 2012-10-10T20:38:20.687 回答