Home > Software design >  What is the name of the special method responsible for `if obj:` statement in an object class which
What is the name of the special method responsible for `if obj:` statement in an object class which

Time:06-03

I have created a custom object that contains __bool__ special method as follows:

class CustomObject:
   def __init__(self, value):
       self.value = value
   def __bool__(self):
       print("This is from the __bool__ method")
       return True
obj = CustomObject(10)
if obj:
    print("Inside if")

output:

This is from the __bool__ method
Inside if

if statement calls the __bool__ special method. However, in the following code, the custom model does not contain the __bool__ special method but still, the condition of the if statement is True:

class CustomObject:
   def __init__(self, value):
       self.value = value

obj = CustomObject(10)
print(dir(obj))
if obj:
    print("Inside if")

output:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'value']
Inside if

So my question is, which of the special methods in the upper section is called by the if statement?

CodePudding user response:

Per Python's documentation on __bool__:

Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.

In other words, if __bool__ doesn't exist, we check __len__() != 0. If __len__ doesn't exist, the answer is always True.

  • Related