phoenix97
phoenix97

Reputation: 209

How to override if of an object?

I have created a class A:

class A:
    def __init__(self, items):
        self.items = items

a=A([1,2])

I want to make it such that I can do if a to get True if there are items in the list and False otherwise. I couldn't find a way to do that. Overriding __eq__ was for comparing the object with another.

Upvotes: 0

Views: 834

Answers (2)

Anustuv Pal
Anustuv Pal

Reputation: 21

In programming terms, the if a in the expression 1 if a else 0 is known as truth value testing. If we look at the truth values of the built-in data types, the truth value will be False for 0 (int), 0.0 (float), '' (str), '[]' or list(), {} or dict(), () or tuple(), set(), and of course False (bool). The result will be True otherwise.

Consider a class A, that has two attributes a1 and a2, which can contain any data type. The instance of A should evaluate to True iff values of both the attributes are true. We have to implement the __bool__ method of the class as shown,

class A:
    def __init__(self, arg1, arg2):
        self.val1 = arg1
        self.val2 = arg2

    def __bool__(self):
        if self.val1 and self.val2:
            return True
        return False

Let's create some instances of this class, and check their truth values in a loop.

a1 = A(0, '')
a2 = A(1.3, [])
a3 = A('', [1, 2])
a4 = A(3, 'x')
for a in [a1, a2, a3, a4]:
    if a:
        print(a.val1, a.val2)
    else:
        print(False)

Output:

False
False
False
3 x

Upvotes: 0

Jiří Baum
Jiří Baum

Reputation: 6930

You can override either the __bool__ method or the __len__ method (or both).

The __bool__ method should return True or False; the __len__ method should return an integer indicating how many items there are in the object, and in an if statement the object will be considered true if this is non-zero.

If both are defined, __bool__ will be preferred for if statements; this can be useful if determining non-empty is faster than counting the elements, or if you need "empty but true" values.

class A:
    def __init__(self, items):
        self.items = items

    # implement either or both:
    
    def __bool__(self):
        return bool(self.items)

    def __len__(self):
        return len(self.items)

See docs: __bool__ method

Upvotes: 1

Related Questions