python - 在 python 3.4.3 中生成对象

标签 python class object iteration

所以我之前不得不尝试在我的代码运行期间生成对象,但每次都失败了。作为一个非常简单的示例,我希望在运行程序时发生注释的事情,以便它生成类 foo 的对象:

class foo:
    def __init__(self, name, amount, bool):
        self.name = name
        self.amount = amount
        self.bool = bool

desired_names = ['name1', 'name2', 'name3']

for x in desired_names:
    #Create objected assigned to the item in list, and give
    #all the objects an amount of 100 and a bool of True
    #This shoudl create:

    #name1  = foo('name1', 100, True)
    #name2  = foo('name2', 100, True)
    #name3  = foo('name3', 100, True)

我环顾四周,没有发现任何我能理解的有用信息。我也不想像以前那样将对象写入新文件然后导入新文件。但是,如果这是执行此操作的唯一方法,请告诉我! :)

非常感谢任何帮助,非常感谢!!!!!!

最佳答案

使用列表组合来存储对象:

desired_names = ['name1', 'name2', 'name3']
objs = [foo(name,100, True) for name in desired_names]

或通过名称访问的字典:

d = {name:foo(name,100, True) for name in desired_names}

关于python - 在 python 3.4.3 中生成对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31325581/

相关文章:

c# - 将项目添加到 List<string> 属性

python - Pywinauto - 有 2 个元素符合条件

python - Pickle:处理更新的类定义

c++ - 如何防止基类的 protected 成员在子类的第二级中仍然被访问?

c++ - 在预期非成员函数指针时传递成员函数指针?

javascript - 使用数组表示法了解何时将属性设置为对象

objective-c - 我们如何比较一个对象的两个类名

python - pandas DataFrame 可以保存非标量值吗?

python - UTF-8 编码 Pandas DataFrame 到 MySQL

java - 强制接口(interface)方法返回值为多个类的通配符