bma*_*ser 1 python runtime dynamic object
我如何在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
Run Code Online (Sandbox Code Playgroud)
和一个字典
{('a': MyClassA), ('b': MyClassB)}
Run Code Online (Sandbox Code Playgroud)
我如何创建动态的两个类之一的实例,取决于我选择'a'或'b'.
有点这样:
somefunc(str):
if 'a': return new MyClassA
if 'b': return new MyClassB
Run Code Online (Sandbox Code Playgroud)
在通话时获得"CLASS B": somefunc('a').println
但是以更优雅和动态的方式(比如我在运行时向dict添加更多类)
您可以创建一个调度程序,它是一个字典,您的键映射到类.
dispatch = {
"a": MyClassA,
"b": MyClassB,
}
instance = dispatch[which_one]() # Notice the second pair of parens here!
Run Code Online (Sandbox Code Playgroud)