繁体   English   中英

如何通过遍历字符串在Python中创建对象?

[英]How can I create objects in Python via iterating through a string?

我从这样的文件中读取一行:

a b c d e f

有了这个字符串,我想在用户类中将每个字母变成一个新的“用户”。 所以我想要的是这样的:

for character in **the first line of the file**:
    if character != ' '
        user = user(character)

换句话说,我想要“ userA = user(“ a”)”之类的东西,其中user是我定义为接收字符串作为参数的类。

我很难找到一种方法来迭代Python中关于文件的字符串,然后使用结果创建对象。

您不能在作业的左侧添加任何内容(您不能以这种方式构造变量名称)。 您应该使用字典和str.split方法:

users = {} # note the plural, this is not 'user', but 'users'
for name in myString.split():
    users[name] = user(name)

您还可以使用字典理解来实现相同目的:

users = { name : user(name) for name in myString.split() }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM