你可以使用一个字符串来实例化python中的类吗? [英] Can you use a string to instantiate a class in python?

查看:421
本文介绍了你可以使用一个字符串来实例化python中的类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用构建器模式来分离一堆不同的配置可能性。基本上,我有一堆被命名为ID(类似ID12345的类)。这些都从基础构建器类继承。在我的脚本中,每次这个应用程序运行时,我需要为每个类实例化一个实例(约50个)。所以,我试图看看,而不是这样做:

I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs. So, I'm trying to see if instead of doing something like this:

ProcessDirector = ProcessDirector()
ID12345 = ID12345()
ID01234 = ID01234()

ProcessDirector.construct(ID12345)
ProcessDirector.construct(ID01234)

ID12345.run()
ID01234.run()

我可以做这样的事情(我知道这不是' t工作):

Can I do something like this (I know this doesn't work):

IDS = ["ID12345", "ID01234"]

ProcessDirector = ProcessDirector()
for id in IDS:
  builder = id() #some how instantiate class from string
  ProcessDirector.construct(builder)
  builder.run()

这样,当我需要在将来添加一个新的,所有我需要做的是添加id IDS列表,而不是在整个代码中弄清新的ID。

That way, when I need to add a new one in the future, all I have to do is add the id to the IDS list, rather than peppering the new ID throughout the code.

看起来根据数据来自哪里有一些不同的意见。这些ID被输入到没有其他人有权访问的文件中。我没有从命令行中读取字符串,并且在将来添加新的ID时,我可以做一点改动。

Looks like there are some different opinions based on where the data is coming from. These IDs are entered in a file that no one else has access to. I'm not reading the strings from the command line, and I'd like to be able to do as little alteration when adding a new ID in the future.

推荐答案

不完全确定这是你想要的,但它似乎是一个更Python的方式来实例化一堆类列在一个字符串中:

Not totally sure this is what you want, but it seems like a more Python'y way to instantiate a bunch of classes listed in a string:

class idClasses:
    class ID12345:pass
    class ID01234:pass
# could also be: import idClasses

class ProcessDirector:
    def __init__(self):
        self.allClasses = []

    def construct(self, builderName):
        targetClass = getattr(idClasses, builderName)
        instance = targetClass()
        self.allClasses.append(instance)

IDS = ["ID12345", "ID01234"]

director = ProcessDirector()
for id in IDS:
    director.construct(id)

print director.allClasses
# [<__main__.ID12345 instance at 0x7d850>, <__main__.ID01234 instance at 0x7d918>]

这篇关于你可以使用一个字符串来实例化python中的类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆