简体   繁体   English

在 python 运行时创建对象

[英]create objects on runtime in python

how do i create object-instances on runtime in python?如何在 python 的运行时创建对象实例?

say i have 2 classes:说我有 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

and a dict和一个字典

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

how can i create dynamic an instance of one of my two classes, depending of i choose 'a' or 'b'.我如何创建我的两个类之一的动态实例,具体取决于我选择“a”或“b”。

kind of this:这样的:

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

to get "CLASS B" on calling: somefunc('a').println在调用时获得“CLASS B”: somefunc('a').println

but in a more elegant and dynamic way (say i add more classes to the dict on runtime)但以更优雅和动态的方式(比如我在运行时向字典添加更多类)

You might create a dispatcher, which is a dictionary with your keys mapping to classes.您可以创建一个调度程序,它是一个将您的键映射到类的字典。

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

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

You create a class instance by calling the class.您可以通过调用 class 创建一个 class 实例。 Your class dict {('a': MyClassA), ('b': MyClassB)} returns classes;您的 class dict {('a': MyClassA), ('b': MyClassB)}返回类; so you need only call the class:所以你只需要调用 class:

classes['a']()

But I get the sense you want something more specific.但我觉得你想要更具体的东西。 Here's a subclass of dict that, when called with a key, looks up the associated item and calls it:这是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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM