views:

43

answers:

2

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!

A: 

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

Ignacio Vazquez-Abrams
"Are there any negative approaches to this approach?" Not really an answer.
Andrew Sledge
+1  A: 

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)
Paulo Scardine
@Paulo Scardine : "I think a class factory is defined as a callable that returns a class (not an instance)" why are you saying that? and why will i create a class that return class and after i should instancy them ?? i think you miss understand the name "class factory"
singularity
@singularity: You use a class factory when your class is not defined in a source file and you need to build the class on the fly, for example, when the class properties and methods are based on dynamic parameters stored in a database. I use this method to create django forms dynamically.
Paulo Scardine
@Paulo Scardine : i don't understand why you are telling me that :) i think my comment was clear but i will repeat it, i was arguing about the definition that you give on a class factory (factory pattern) when you said that a class factory should return class and not instance because it's not; and i told you that you miss understood the name "class factory" to make it easier class factory is a "class that implement the factory pattern" and not as you thought "a factory pattern that return class". hopefully this can clear things :)
singularity
@singularity: may be you are right and I misread http://en.wikipedia.org/wiki/Factory_method_pattern
Paulo Scardine