2017-09-29 30 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