我有一个方法,涉及一个很长的 if/elif block 来转换所提供对象的属性。我想避免使用两种方法。如果该方法可以采用可迭代列表或不可迭代的单个对象,那么如果该对象不可迭代,如何使 if/elif block 仍然执行?
现在我的代码基本上如下所示:
def convert_orders(orders, orderid=None):
"""Converts certain fields of an order object to readable and/or indexable values"""
status = None
color = None
order = None
converted = []
if not orders:
order = session.query(Order).filter(Order.orderid == orderid)
for order in orders:
# convert order status to a string and give it a color for the tables
if order.status == 0:
status = 'In Progress'
color = QColor(150, 255, 250)
elif order.status == 1:
status = 'Ready'
color = QColor(60, 255, 75)
# elif continues below for another 70+ lines, converting other attributes.
如果 orders
作为列表提供,但此方法也可以采用 orderid
(整数),我如何仅使用一个 elif block 来转换任一类型,具体取决于是在哪一个上提供的?该方法可以使用一种类型或另一种类型来调用,但绝不能同时使用两种类型。
最佳答案
if not orders:
...
orders = (order,)
关于python - 在 Python 中使用可选的 For 子句遵守 DRY 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498152/