0

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!

Community
  • 1
  • 1
bradreaves
  • 1,463
  • 2
  • 14
  • 16
  • 1
    changing `__type__` is more than dangerous; it is crazy. There are far better ways to proceed. – S.Lott Oct 20 '10 at 22:49

2 Answers2

1

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
  • 73,447
  • 11
  • 124
  • 153
  • "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" – mouad Oct 20 '10 at 23:24
  • @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 Oct 21 '10 at 03:21
  • 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 :) – mouad Oct 21 '10 at 10:05
  • @singularity: may be you are right and I misread http://en.wikipedia.org/wiki/Factory_method_pattern – Paulo Scardine Oct 21 '10 at 10:52
-1

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

Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358