您可以使用字符串实例化类吗?

您可以使用字符串实例化类吗?,第1张

您可以使用字符串实例化类吗?

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

class idClasses:    class ID12345:pass    class ID01234:pass# could also be: import idClassesclass 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>]


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5674721.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存