ArtOfWarfare
ArtOfWarfare

Reputation: 21476

Is it possible to overload logical and in Python?

I was under the impression it was possible to overload and in Python, but reading through the docs just now, I realized that __and__ refers to the bitwise & operator, not logical and.

Am I overlooking something, or is it not possible to overload logical and in Python?

Upvotes: 7

Views: 4298

Answers (3)

Salailah
Salailah

Reputation: 445

No this is not possible. There is a proposal that adds this functionality but for now, it is rejected.

Upvotes: 12

Juuso Meriläinen
Juuso Meriläinen

Reputation: 611

There is no straight way to do this. You could override __nonzero__ for your objects to modify their truth value.

class Truth:

    def __init__(self, truth):
        self.truth = truth

    def __nonzero__(self):
        return self.truth

t = Truth(True)
f = Truth(False)

print bool(t and t)
print bool(t and f)
print bool(f and f)

Upvotes: 2

rkrzr
rkrzr

Reputation: 1912

No, it is not possible. See here.

Upvotes: 2

Related Questions