如何创建 class returns 个不同的对象

How to create a class that returns different objects

我正在尝试执行以下操作:

#A wrapper object that based on it's parameters returns other objects
class A():
   def __new__(cls, config):
     if config.type == "1":
       return C(config)
     elif config.type == "2":
       return D(config)   

你怎么称呼这个模式,在python中你是怎么做的? __new__ 似乎不接受参数。

__new__ 确实接受参数,它可以用作其他 类 的工厂,就像您的示例尝试做的那样。来自 The standard type hierarchy

Classes are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override new(). The arguments of the call are passed to new() and, in the typical case, to init() to initialize the new instance.

一个有效的例子是

class C:

    def __init__(self, val):
        self.what = "C"
        print("i am C")

class D:
    
    def __init__(self, val):
        self.what = "D"
        print("i am D")

class A():
   def __new__(cls, config):
     if config == "1":
       return C(config)
     elif config == "2":
       return D(config)
   
foo = A("1")
print(foo.what, type(foo))
bar = A("2")
print(bar.what, type(bar))