Python类,如何跳过错误的条目并继续下一个条目



我创建了这个Python类,用于输入一些新产品、旧产品或翻新产品(通过.lower()函数实现不区分大小写(。条件参数的任何其他条目都应该给出一个错误(ValueError(,我希望代码继续到下一行。

CCD_ 2是第一个也是最完善的新对象。这没有问题。我对下一个对象Random_Product_2的条件犯了一个故意的错误。这应该打印ValueError。它做了,但也有额外的错误。这导致代码在其轨道上停止。生成对象的下一行代码(输入正确的条件值(根本不会运行。

我基本上是在尝试将Random_Product_2等错误条目的代码跳过到下一行代码。到目前为止,这是我的基本代码,一旦我解决了这个问题,我计划在此基础上构建其他东西。

class Product:
def __init__(self, Id, price, inventory, condition):
self.condition = condition.lower()
if self.condition != "new" and self.condition != "used" and self.condition != "refurbished":
raise ValueError('condition can only be new or used or refurbished')
self.Id = Id
self.price = price
self.inventory = inventory
Random_Product_1 = Product('What_is_this', 50, 81, "Used") # defined perfectly
Random_Product_2 = Product('What_is_this', 50, 85, "Useed") # not defined at all, code doesn't go to next line
Random_Product_3 = Product('What_is_this', 500, 805, "Used") # This is not run

如果我理解正确,您选择引发一个异常,这样就根本不会创建具有非法值的实例,因此以后不必处理它。为什么不呢?但是,要使程序在引发异常后继续运行,需要使用try语句。让我们在一个循环中创建产品,并在这个循环中只使用一个try语句:

class Product:
def __init__(self, Id, price, inventory, condition):
self.condition = condition.lower()
if self.condition not in ("new", "used", "refurbished"):
raise ValueError('condition can only be new or used or refurbished')
self.Id = Id
self.price = price
self.inventory = inventory
# special method for a more readable print()
def __repr__(self):
return "{}t{}t{}t{}".format(self.Id, self.price, self.inventory, self.condition)
data = (('A', 50, 81, "Used"),
('B', 50, 85, "Useed"), 
('C', 500, 805, "Used"))
product_list = []
for item in data:
try:
new_product = Product(*item)
except:
# do nothing with the exception
pass
else:
product_list.append(new_product)
# check if product 'B' exists
for item in product_list:
print(item)

输出:

A   50  81  used
C   500 805 used

您的问题描述并不精确:if语句无法"跳到下一个条目",因为下一个条目的控制程序是调用程序,而不是__init__。在初始化器中所能做的就是控制这个一个对象的设置。

根本问题是你你希望程序继续,但你使用了一种语言工具,特别中止了程序。很简单,你需要决定你想要哪一个。假设您希望尽可能顺利地完成当前初始化,请尝试以下操作:对照有效选项列表检查给定的选项。如果它不在该列表中,请发出一条简单的消息,并尽可能完成初始化。

def __init__(self, Id, price, inventory, condition):
valid_condition = ("new", "used", "refurbished")
self.condition = condition.lower()
if self.condition not in valid_condition:
print('condition can only be new or used or refurbished. ',
'Setting to "unknown"')
self.condition = "unknown"
self.Id = Id
self.price = price
self.inventory = inventory

这就是你想要的效果吗?

相关内容

最新更新