Nov-16-2017, 07:16 PM
I have a situation where I know what superclass I am creating (using the superclass sort of like a java abstract class), and will be receiving an string argument to control which type of subclass I return. Here is a simplified snippet that accomplishes what I'm trying to do:
class Person:
def __init__(self, pet_types):
self.pets = [Pet().factory(t) for t in pet_types]
def get_pets(self):
print([pet.name for pet in self.pets])
class Pet:
def factory(self, t):
klass = next((cls for cls in self.__class__.__subclasses__() if cls.__name__ == t), self.__class__)
return klass()
def __init__(self):
self.name = 'unknown'
class Cat(Pet):
def __init__(self):
self.name = 'Garfield'
class Dog(Pet):
def __init__(self):
self.name = 'Fido'
Person(['Cat', 'Dog', 'Bird']).get_pets()It works, but I'm wondering if there is a more pythonic (or just, programming practices in general) way of doing this. Or if this is a "code smell". For context, I'm receiving a json file which defines object types.
