你能用一个字符串来实例化一个类吗? [英] Can you use a string to instantiate a class?

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

问题描述

我正在使用构建器模式来分离一堆不同的配置可能性.基本上,我有一堆名为 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()

我可以这样做吗(我知道这行不通):

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 时,我所要做的就是将 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.

推荐答案

不确定这是您想要的,但它似乎是一种更 Pythonic 的方式来实例化列在字符串中的一堆类:

Not sure this is what you want but it seems like a more Pythonic 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>]

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

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