2

I have defined a class in Python 3 and have a case that I create an "empty" class object. Therefor I want to be able to check if the object is empty or not, like you can write:

test = []
if not test:
    print('False')

My code for the class looks like this (note that I will accept an empty value for name):

class myClass:
    def __init__(self, name=False):
        self.name = name

    def __str__(self):
         return self.name.replace('\n', ' ')

    def __repr__(self):
         return self.name.replace('\n', ' ')

    def __eq__(self, other):
         if not isinstance(other, myClass):
             return False

         if not self.name and not other.name:
              pass

         elif not (self.name or other.name):
              return False

         elif self.name != other.name:
                 return False

         return True

Now I would like to check if I got an empty class:

test = myClass()
if not test:
    print('False')
else:
    print('True')

The result of this case will always be true. How can I change this behaviour?

JBecker
  • 94
  • 7
  • @GinoMempin If I get that correct, I would define __bool__(self) like if self == myClass() return False else return True and that would do the job? – JBecker Feb 11 '21 at 10:39

1 Answers1

1

Add a __bool__ method to your class:

def __bool__(self):
    return bool(self.name)

To cater for the case where self.name == '' and you want to return True:

def __bool__(self):
    return self.name is not False
Cyttorak
  • 12,969
  • 3
  • 16
  • 38