代码之家  ›  专栏  ›  技术社区  ›  Ponkadoodle

为自定义类[重复]重写bool()。

  •  46
  • Ponkadoodle  · 技术社区  · 15 年前

    这个问题已经有了答案:

    我只想让bool(myinstance)返回false(对于myinstance,在条件(如if/or/and)中计算为false)。我知道如何覆盖>、<、=)

    我试过了:

    class test:
        def __bool__(self):
            return False
    
    myInst = test()
    print bool(myInst) #prints "True"
    print myInst.__bool__() #prints "False"
    

    有什么建议吗?

    (我使用的是python 2.6)

    6 回复  |  直到 6 年前
        1
  •  64
  •   Ethan Furman    9 年前

    这是python 2.x还是python 3.x?对于python 2.x,您希望覆盖 __nonzero__ 相反。

    class test:
        def __nonzero__(self):
            return False
    
        2
  •  56
  •   John La Rooy    15 年前

    如果您想让代码与python3保持兼容,可以这样做

    class test:
        def __bool__(self):
            return False
        __nonzero__=__bool__
    
        3
  •  8
  •   IceArdor    6 年前

    如果你 test 类类似于列表,定义 __len__ bool(myInstanceOfTest) 将返回 True 如果有1+个项目(非空列表)和 False 如果有0个项目(空列表)。这对我有用。

    class MinPriorityQueue(object):
        def __init__(self, iterable):
            self.priorityQueue = heapq.heapify(iterable)
        def __len__(self):
            return len(self.priorityQueue)
    
    >>> bool(MinPriorityQueue([])
    False
    >>> bool(MinPriorityQueue([1,3,2])
    True
    
        4
  •  5
  •   Ignacio Vazquez-Abrams    15 年前
        5
  •  2
  •   tknickman    8 年前

    与John la Rooy类似,我使用:

    class Test(object):
        def __bool__(self):
            return False
    
        def __nonzero__(self):
            return self.__bool__()
    
        6
  •  2
  •   jhp    8 年前

    [这是@john la rooy对答案的评论,但我还不能评论:)]

    为了与python3的兼容性,您可以这样做(我在找这个)

    class test(object):
        def __bool__(self):
            return False
    
        __nonzero__=__bool__
    

    唯一的问题是你需要重复 __nonzero__ = __bool__ 每次你换衣服 __bool__ 在子类中。否则 __nonzero__ 将远离超类。你可以试试

    from builtins import object  # needs to be installed !
    
    class test(object):
        def __bool__(self):
            return False
    
        __nonzero__=__bool__
    

    它应该可以工作(未确认)或者编写一个元类:)您自己。