如果>>条件太多

时间:2018-11-06 19:13:43

标签: python django

我在这里有几个条件和“子条件”。看起来很乱,我想知道您是否知道在这里编写此代码的更好方法?

def form_valid(self, form):
    instance = form.instance

    # Conditions
    if instance.available_amount <= instance.redeemed_amount:
        instance.status = Discount.STATUS_NO_MORE_LEFT
    elif instance.valid_until <= timezone.now():
        instance.status = Discount.STATUS_EXPIRED

    # Conditions to set active
    elif instance.status == Discount.STATUS_NO_MORE_LEFT:
        if instance.available_amount > instance.redeemed_amount:
            instance.status = Discount.STATUS_ACTIVE
    elif instance.status == Discount.STATUS_EXPIRED:
        if instance.valid_until > timezone.now():
            instance.status = Discount.STATUS_ACTIVE

1 个答案:

答案 0 :(得分:-2)

我有2条建议:

使用and关键字并将您的条件分为两行以提高可读性:

elif (instance.status == Discount.STATUS_NO_MORE_LEFT
      and instance.available_amount > instance.redeemed_amount):
    instance.status = Discount.STATUS_ACTIVE
elif (instance.status == Discount.STATUS_EXPIRED 
      and instance.valid_until > timezone.now()):
    instance.status = Discount.STATUS_ACTIVE

使用较短的变量名来减少行长(进而减少“混乱”):

inst= form.instance
obj = form.instance
x = form.instance
# the latter is shorter but too vague