Let's say I want to have an object that instantiates classes depending on the input and returns it when called.
from pets import Dog, Cat
class PetCreator:
@classmethod
def __call__(cls, pet_type):
if pet_type == "cat": return Cat()
elif pet_type == "dog": return Dog()
else: raise SomeError
def pet_creator(pet_type):
if pet_type == "cat": return Cat()
elif pet_type == "dog": return Dog()
else: raise SomeError
if __name__ == "__main__":
fav_pet_type = input() # "cat"
my_cat = pet_creator(fav_pet_type) #this?
my_cat = PetCreator(fav_pet_type) #or that?
Which design is more pythonic? And why would you choose one over the other
Aucun commentaire:
Enregistrer un commentaire