在python运行时创建对象

在python运行时创建对象,python,object,dynamic,runtime,Python,Object,Dynamic,Runtime,如何在python运行时创建对象实例 假设我有两门课: 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): s

如何在python运行时创建对象实例

假设我有两门课:

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


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

您可以创建一个dispatcher,它是一个字典,其中键映射到类

dispatch = {
    "a": MyClassA,
    "b": MyClassB,
}

instance = dispatch[which_one]() # Notice the second pair of parens here!

您可以创建一个dispatcher,它是一个字典,其中键映射到类

dispatch = {
    "a": MyClassA,
    "b": MyClassB,
}

instance = dispatch[which_one]() # Notice the second pair of parens here!

通过调用类来创建类实例。您的类dict
{('a':MyClassA),('b':MyClassB)}
返回类;因此,您只需调用类:

classes['a']()
但我感觉你想要更具体的东西。下面是
dict
的一个子类,当使用键调用它时,它会查找相关项并调用它:

>>> class ClassMap(dict):
...     def __call__(self, key, *args, **kwargs):
...         return self.__getitem__(key)(*args, **kwargs)
... 
>>> c = ClassMap()
>>> c['a'] = A
>>> c['b'] = B
>>> c('a')
<__main__.A object at 0x1004cc7d0>
类类映射(dict): ... 定义调用(self、key、*args、**kwargs): ... 返回self.\uuuu getitem\uuuuuuu(键)(*args,**kwargs) ... >>>c=ClassMap() >>>c['a']=a >>>c['b']=b >>>c(‘a’)
通过调用类来创建类实例。您的类dict
{('a':MyClassA),('b':MyClassB)}
返回类;因此,您只需调用类:

classes['a']()
但我感觉你想要更具体的东西。下面是
dict
的一个子类,当使用键调用它时,它会查找相关项并调用它:

>>> class ClassMap(dict):
...     def __call__(self, key, *args, **kwargs):
...         return self.__getitem__(key)(*args, **kwargs)
... 
>>> c = ClassMap()
>>> c['a'] = A
>>> c['b'] = B
>>> c('a')
<__main__.A object at 0x1004cc7d0>
类类映射(dict): ... 定义调用(self、key、*args、**kwargs): ... 返回self.\uuuu getitem\uuuuuuu(键)(*args,**kwargs) ... >>>c=ClassMap() >>>c['a']=a >>>c['b']=b >>>c(‘a’)