I have to following problem. I have a data input, in which a type (animal in the following example) is defined. Based on this type, I need different subclasses, because I want to have different attributes, based on the type. Here is an example:
class pet:
def __init__(self, dict):
self.name = dict['name']
self.type = dict['type']
class dog(pet):
def __init__(self, dict):
pet.__init__(self, dict)
self.weight = dict['weight']
class cat(pet):
def __init__(self, dict):
pet.__init__(self, dict)
self.color = dict['color']
if __name__ == '__main__':
pet1 = {'name': 'Harry', 'type': 'dog', 'weight': 100}
pet2 = {'name': 'Sally', 'type': 'cat', 'color': 'blue'}
mypet1 = pet(pet1)
mypet2 = pet(pet2)
I would like to convert the pet objects to a dog or a cat resp., based on the type argument automatically. The last point is crucial, since there will be many pets and I cannot read the type by hand and use the corresponding subclass explicitly. Is there a way to do this?
Thanks in advance