Python:如果三个以上的东西都是真的,返回false [英] Python: if more than one of three things is true, return false
问题描述
优惠券可以有三种类型:终身账户凭证,特定期间月凭证,一定数量的美元凭证。
为了保持简单,我只允许优惠券拥有三种可能的值之一(即凭证不能为10美元和5个月)。但是,我想检查一个优惠券是否被保存,以确保这个规则是真实的。
目前我有:
true_count = 0
如果self.months:
true_count + = 1
如果self.dollars:
true_count + = 1
如果self.lifetime:
true_count + = 1
如果true_count> 1 $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
我知道有一个更好的方式来做到这一点,但我没有看到它(称为编码器的块)。
帮助非常感谢。
如果它是maters,三种类型是int,int和bool
months = models.IntegerField(default = 0)
cents = models.IntegerField(default = 0)
#dollars = models.FloatField(default = 0.00)
#dollars每个小组的建议的整数为
lifetime = models.BooleanField(default = False)
解决方案在类似的情况下,我做了一件事是这样的:
coupon_types =
true_count = sum(如果ct为coupon_types,则为1)
如果true_count> 1 $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
将来更容易添加新的优惠券类型进行检查!
I'm writing a django model that allows my site to have coupons.
Coupons can have three types: lifetime account voucher, certain period of months voucher, certain number of dollars voucher.
To keep things simple, I'm only allowing coupons to have one of the three possible values (i.e. a voucher can't be for $10 and 5 months). But I want to check when a coupon is being saved to ensure this rule is true.
Currently I have:
true_count = 0
if self.months:
true_count += 1
if self.dollars:
true_count += 1
if self.lifetime:
true_count += 1
if true_count > 1:
raise ValueError("Coupon can be valid for only one of: months, lifetime, or dollars")
I know there's a better way to do this, but I'm not seeing it (call it coder's block).
Help is much appreciated.
In case it maters, the three types are int, int, and bool
months = models.IntegerField(default=0)
cents = models.IntegerField(default=0)
#dollars = models.FloatField(default=0.00)
#dollars replaced with integer cents per advice of group
lifetime = models.BooleanField(default=False)
解决方案 One thing I've done in similar situations is this:
coupon_types = (self.months, self.dollars, self.lifetime,)
true_count = sum([1 for ct in coupon_types if ct])
if true_count > 1:
raise ValueError("Coupon can be valid for only one of: months, lifetime, or dollars")
It's now much easier to add new coupon types to check for in the future!
这篇关于Python:如果三个以上的东西都是真的,返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!