0

我有产品库存程序并在菜单文件中具有修改产品功能

def modify_product(self):
    id = input("Enter product id: ")
    type = input("Enter product type: ")
    price = input("Enter product price: ")
    quantity = input("Enter product quantity: ")
    description = input("Enter product description: ")
    if type:
        self.inventor.modify_type(id, type)
    if price:
        self.inventor.modify_price(id, price)    
    if quantity:
        self.inventor.modify_quantity(id, quantity)   
    if description:
        self.inventor.modify_description(id, description) 

我收到错误:AttributeError: 'NoneType' object has no attribute 'type'

这是我在文件inventor.py 中的 modify_type,price,quantity,description 函数:

def modify_type(self, product_id, type=''):
    self._find_product(product_id).type = type

def modify_price(self, product_id, price):
    self._find_product(product.id).price = price

def modify_quantity(self, product_id, quantity):
    self._find_product(product.id).quantity = quantity

def modify_description(self, product_id, quantity):
    self._find_product(product.id).description = description

这是 _find_product 函数:

def _find_product(self, product_id):
    for product in self.products:
        if str(product.id) ==(product.id):
            return product
        return None
4

1 回答 1

1

您的self._find_product()电话正在返回None,因为您没有在循环中测试正确的值。

不要测试str(product.id) againstproduct.id but against theproduct_id` 参数:

if str(product.id) == product_id:

你也回来None得太早了。该return语句是多余的,只需将其删除。如果函数结束时没有return,None默认返回:

def _find_product(self, product_id):
    for product in self.products:
        if str(product.id) == product_id:
            return product

这可以折叠成:

def _find_product(self, product_id):
    return next((p for p in self.products if str(p.id) == product_id), None)
于 2013-05-30T10:16:19.643 回答