I'm attempting to create what a believe (in my ignorance) is known as a class factory. Essentially, I've got a parent class that I'd like to take an __init__
argument and become one of several child classes. I found an example of this recommended on StackOverflow here, and it looks like this:
class Vehicle(object):
def __init__(self, vtype):
self.vtype = vtype
if vtype=='c':
self.__class__ = Car
elif vtype == 't':
self.__class__ = Truck
I've heard that changing __type__
can be dangerous. Are there any negative approaches to this approach? I'd use a function to dynamically create objects, but it wouldn't work with the existing code I'm using. It expects a class where I plan to do the dynamic type change.
Thanks!