开发者

Consequences of changing __type__

开发者 https://www.devze.com 2023-01-20 21:37 出处:网络
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 chil

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(ob开发者_如何学Cject):
  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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消