Skip to main content
 首页 » 编程设计

python之在运行时在 python 中创建对象

2025年05月04日12cmt

我如何在 Python 运行时创建对象实例?

假设我有 2 个类:

class MyClassA(object): 
    def __init__(self, prop): 
        self.prop = prop 
        self.name = "CLASS A" 
 
    def println(self): 
        print self.name 
 
 
class MyClassB(object): 
    def __init__(self, prop): 
        self.prop = prop 
        self.name = "CLASS B" 
 
    def println(self): 
        print self.name 

和一个字典

{('a': MyClassA), ('b': MyClassB)} 

我如何创建我的两个类之一的动态实例,具体取决于我选择“a”还是“b”。

这样的:

somefunc(str): 
    if 'a': return new MyClassA 
    if 'b': return new MyClassB 

在调用时获得“CLASS B”:somefunc('a').println

但以更优雅和动态的方式(比如我在运行时向字典添加更多类)

请您参考如下方法:

您可以创建一个调度程序,它是一个字典,其中包含您的键映射到类。

dispatch = { 
    "a": MyClassA, 
    "b": MyClassB, 
} 
 
instance = dispatch[which_one]() # Notice the second pair of parens here!