【问题标题】:Python - How to declare when an instance is True or FalsePython - 如何声明实例何时为 True 或 False
【发布时间】:2019-03-16 21:24:44
【问题描述】:

我正在从 collections.abc 覆盖 MutableSet,并且我希望能够确定它的实例何时等于 True/False。

我知道用于比较的神奇方法,但我正在寻找诸如检查 Python 提供的空集/列表之类的行为。

class Example():
    pass

e = Example()

if e:
    print("This shall work - the default of an instance is True")

# What I'd like is something similar to...

if []:
    pass
else:
    print("This shall be false because it's empty, there wasn't a comparison")

我看过食谱:Special methodsData model - Other various websites - 我似乎找不到答案:(

最终我希望能够去:

class A:
    def __init__(self, value: int):
        self.value = value

    def __cool_equality_method__(self):
        return self.value > 5

a = A(10)
b = A(3)

if a:
    print("This happens")
if b:
    print("This doesn't happen")

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    __bool__ 简单呢?

    class A:
        def __bool__(self):
            if not getattr(self, 'trueish', None):
                return False
            else:
                return True
    
    a = A()
    if a:
        print("Hello")
    a.trueish = True
    if a:
        print("a is True")
    

    【讨论】:

      【解决方案2】:

      你需要在你的类上实现__bool__方法,这只是你的旧__cool_equality_method__重命名为__bool__

      class A:
          def __init__(self, value: int):
              self.value = value
      
          def __bool__(self):
              return self.value > 5
      
      a = A(10)
      b = A(3)
      
      if a:
          print("This happens")
      if b:
          print("This doesn't happen")
      
      """
      This happens
      """
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-14
        • 1970-01-01
        • 1970-01-01
        • 2020-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多