I have a function where sometimes a parameter can be none, and I would like to compare that with another object. However, if I am trying to call an object property, my script will throw an exception on None, even if both objects are None (see example below).
def do_animals_make_same_sound(first_animal, second_animal):
if first_animal.sound = second_animal.sound:
print('Yes they do!')
But if both animals are None, it throws an exception when instead I want it to print('Yes they do!'), but it seems I have to write a really ugly If statement:
def do_animals_make_same_sound(first_animal, second_animal):
if (first_animal is None and second_animal is None) or (first_animal is not None and first_animal.sound == second_animal.sound):
print('Yes they do!')
Is there a better way to do this?
Aucun commentaire:
Enregistrer un commentaire