Python 属性错误:';非类型';对象没有属性';类型';
我有产品库存程序,并在菜单文件中具有修改产品功能Python 属性错误:';非类型';对象没有属性';类型';,python,python-3.x,attributes,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("Ente
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'对象没有属性'type'
以下是文件inventor.py中的“修改类型、价格、数量、描述”函数:
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
以下是"查找"产品功能:
def _find_product(self, product_id):
for product in self.products:
if str(product.id) ==(product.id):
return product
return None
您的
self.\u find\u product()
调用返回None
,因为您没有在循环中测试正确的值
不要针对product.id而针对
product\u id`参数测试str(product.id):
if str(product.id) == product_id:
您还太早返回了None
。return
语句是多余的,只需删除它即可。如果函数结束时没有返回
,默认情况下返回无:
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)
提示:您从
\u find\u product(product.id)
中得到了什么?我设法预测了您的错误来自何处,但下次一定要包括对错误的完整跟踪,而不仅仅是异常本身。微不足道的缩进错误。您缩进返回None
的次数太多了。谢谢,也许我需要一个数据库来保存产品信息,或者更好地保存在txt或excel文件中?也许。在不了解您的用例、经验水平和环境的情况下,我无法以任何程度的确定性告诉您。这是一个太宽泛的问题,无法在评论中回答。:-)谢谢你的帮助,我想首先我会把所有的信息都写进txt,也许以后我会把这些信息转移到数据库中