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