AttributeError:'NoneType'对象没有属性'type'

时间:2013-05-30 10:12:59

标签: python python-3.x attributes

我有产品库存程序和菜单文件中的修改产品功能

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

1 个答案:

答案 0 :(得分:1)

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

请勿测试str(product.id) against product.id but against the product_id`参数:

if str(product.id) == product_id:

您也过早地返回Nonereturn语句是多余的,只需将其删除即可。如果函数在没有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)