【问题标题】:creating an instance in a for loop在 for 循环中创建实例
【发布时间】:2018-04-02 13:21:46
【问题描述】:

我正在尝试通过 dir() 提取类名,并通过 for 循环中的变量名动态创建它们的实例。如何让 python 将“项目”解释为变量名而不是“不存在的”类名。

>>> class cls1():
...     def __init__(self):
...         self.speak = 'say cls1'
...     def replay(self):
...         print self.speak
...
>>> for item in dir():
...     if item[:2] != '__':
...         print 'item = ', item
...         x = item()
...         x.reply()
...
item =  cls1
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
TypeError: 'str' object is not callable

【问题讨论】:

    标签: python instance


    【解决方案1】:

    dir() 产生一个排序的名字列表;这些只是字符串。它们不是对实际对象的引用。不能对字符串应用调用。

    改用globals() dictionary,这会为您提供名称和实际对象的映射:

    for name, obj in globals().items():
        if not name.startswith('__'):
            print "name =", name
            instance = obj()
            instance.replay()
    

    dir() 在模块级别,不带参数,本质上返回sorted(globals())

    【讨论】:

    • 想再问你一个问题……Python中没有办法将字符串评估为类名。也许通过评估?换句话说,我认为这个字符串可以与类名匹配,然后自动转换为引用。谢谢
    • @Kris: eval 只能作为最后的手段使用。 globals() 字典为您提供了从字符串值到对象的直接映射。如果您只有变量name 中的字符串名称,那么globals()[name] 会为您提供对象。
    • 谢谢。只是为了澄清-您的示例在上面有效,一切都很好。只是想知道这样做的替代方法(和不太理想的方法)。再次感谢。
    猜你喜欢
    • 2013-04-18
    • 2018-12-20
    • 1970-01-01
    • 2018-04-10
    • 2020-03-31
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多