有没有一种方法来否定返回到变量的布尔值?
问题描述:
我有一个Django站点,它有一个Item
对象,它有一个布尔型属性active
。我愿做这样的事情,从假属性切换为True,反之亦然:有没有一种方法来否定返回到变量的布尔值?
def toggle_active(item_id):
item = Item.objects.get(id=item_id)
item.active = !item.active
item.save()
这句法是许多基于C的语言有效,但在Python似乎无效。是否有另一种方式来做到这一点没有用:
if item.active:
item.active = False
else:
item.active = True
item.save()
天然蟒蛇neg()
方法似乎返回一个整数的否定,而不是一个布尔值的否定。
感谢您的帮助。
答
你可以这样做:
item.active = not item.active
这应该做的伎俩:)
答
item.active = not item.active
是Python的方式
答
我想你想
item.active = not item.active
答
的布尔的否定是not
。
def toggle_active(item_id):
item = Item.objects.get(id=item_id)
item.active = not item.active
item.save()
谢谢你们,那是一个闪电般的快速反应!
答
其简单的事:
item.active = not item.active
所以,最后你会结束:
def toggleActive(item_id):
item = Item.objects.get(id=item_id)
item.active = not item.active
item.save()
答
另(较小
简洁
可读,更算术)的方式来做到这将是:
item.active = bool(1 - item.active)
+1 OMG,从来不知道这是可能的,它确实有道理,但我从来没有想过它!很好的答案! (尽管'bool(1-True)'比'not True'慢一点) –
可能的,是的。有用?不见得!大多数语言都可以做很多这样的丑陋事情,但这对大多数读者来说是非常混乱的。也许在一个非常特殊的情况下这可能是有道理的... – BuvinJ