【问题标题】:Is there a way to negate a boolean returned to variable?有没有办法否定返回到变量的布尔值?
【发布时间】:2011-12-01 00:23:41
【问题描述】:

我有一个 Django 站点,其中有一个 Item 对象,该对象具有一个布尔属性 active。我想做这样的事情来将属性从 False 切换到 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()

原生 python neg() 方法似乎返回整数的否定,而不是布尔值的否定。

感谢您的帮助。

【问题讨论】:

    标签: python django


    【解决方案1】:

    你可以这样做:

    item.active = not item.active
    

    这应该可以解决问题:)

    【讨论】:

      【解决方案2】:

      我想你想要

      item.active = not item.active
      

      【讨论】:

        【解决方案3】:

        布尔值的否定是not

        def toggle_active(item_id):
            item = Item.objects.get(id=item_id)
            item.active = not item.active
            item.save()
        

        谢谢大家,这是一个闪电般的快速响应!

        【讨论】:

          【解决方案4】:

          item.active = not item.active是pythonic的方式

          【讨论】:

            【解决方案5】:

            另一种(简洁可读性更强,算术更多)的方法是:

            item.active = bool(1 - item.active)
            

            【讨论】:

            • +1 OMG,从来不知道这是可能的,这确实有道理,但我从来没想过!很好的答案! (虽然bool(1-True)not True 慢一点)
            • 可能,是的。有用?不见得!几乎任何语言都可以做很多这样丑陋的事情,但这对大多数读者来说是非常混乱的。也许在一个非常特殊的情况下,这可能是有道理的......
            【解决方案6】:

            做起来很简单:

            item.active = not item.active
            

            所以,最后你会得到:

            def toggleActive(item_id):
                item = Item.objects.get(id=item_id)
                item.active = not item.active
                item.save()
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-07-09
              • 2021-01-29
              • 2015-05-25
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-02-10
              • 2018-05-13
              相关资源
              最近更新 更多