Search code examples
pythonpython-3.xclassif-statementself

What does "if self:" mean?


Example:

class Bird:
    def __init__(self):
        self.sound = "chirp!"

    def reproduce_sound(self):
        if self:
            print(self.sound)

bird = Bird()
bird.reproduce_sound()

What does if self: mean? What is the case where the reproduce_sound function call prints nothing?


Solution

  • It checks the truth value of the instance and only prints if it is True. In your example the check doesn't do anything useful and will always print something. You can override the __bool__ method to change its default behaviour.

    For example:

    class Bird:
        ...
        def __bool__(self):
            return bool(self.sound)
    

    Then:

    b = Bird()
    b.reproduce_sound()   # Prints "chirp!"
    b.sound = 0           # or any falsy value, such as None or ""
    b.reproduce_sound()   # Won't print anything because b == False