Class that returns False with bool(TheClassItself)

后端 未结 1 2125
孤街浪徒
孤街浪徒 2021-02-19 05:29

I want to create a class MyClass where bool(MyClass) returns False. Is it possible?

I want this behavior with the class itself, no

1条回答
  •  面向向阳花
    2021-02-19 05:49

    To define the __bool__ method used by a class, not its instances, you need to modify its class. You do that by writing a metaclass.

    class FalseMeta(type):
        def __bool__(self):
            return False
    
    class MyClass(metaclass=FalseMeta):
        pass
    
    print(bool(MyClass))  # False
    

    0 讨论(0)
提交回复
热议问题