lundi 7 août 2017

Python 3 vs 2: if statement on objects and __nonzero__ [duplicate]

I'm trying to port something from Python 2 to 3, and have run into something that appears to be an important difference, but that I'm having trouble finding information about by googling. Consider the following:

class TestClass:
    def __nonzero__(self):
        print("nonzero called")
        return True

instance = TestClass()
if instance:
    pass

If I run this code in Python 2, it prints "nonzero called", but if I run it in Python 3, it does not. So it seems like in Python 3, if statements on objects are evaluated some other way? What's going on here?

Thanks!

Aucun commentaire:

Enregistrer un commentaire