2017-09-29 31 views
1

我有一个涉及非常长的if/elif块来转换提供对象的属性的方法。我想避免使用两种方法。如果该方法可以采用可迭代列表或不可迭代的单个对象,那么如果if/elif块仍然可以执行(如果该对象不可迭代),该如何执行?在Python中使用可选的For语句坚持干DRY的最佳方法

现在我的代码基本上是这样的:

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块要么转换类型,取决于提供的是什么?该方法是用一种或另一种类型调用的,但从来都不是。

+0

最简单的事情就是要求'orders'是可迭代的。单身人士列表'convert_orders([my_one_order])'而不是'convert_orders(my_one_order)''有什么问题? – chepner

回答

1
if not orders: 
    ... 
    orders = (order,) 
+0

'AttributeError:'list_iterator'对象没有属性'status'' – smallpants