python – Consequences of changing __type__ – Education Career Blog

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.



I think a class factory is defined as a callable that returns a class (not an instance):

def vehicle_factory(vtype):
    if vtype == 'c':
        return Car
    if vtype == 't':
        return Truck

VehicleClass = vehicle_factory(c)
vehicle_instance_1 = VehicleClass(*args, **kwargs)
VehicleClass = vehicle_factory(t)
vehicle_instance_2 = VehicleClass(*args, **kwargs)


Don’t do it this way. Override __new__() instead.

Leave a Comment