如何通过迭代字符串在Python中创建对象?

Alw*_*ing -1 python string iteration character object

我从文件中读出一行如下:

a b c d e f
Run Code Online (Sandbox Code Playgroud)

使用此字符串,我想将每个字母转换为我的用户类中的新"用户".所以我想要的是:

for character in **the first line of the file**:
    if character != ' '
        user = user(character)
Run Code Online (Sandbox Code Playgroud)

换句话说,我想要像"userA = user("a")"这样的东西,其中user是我定义的一个类,它接受一个字符串作为参数.

我很难找到在Python中迭代字符串的方法,然后使用结果创建一个对象.

Gez*_*ore 6

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

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

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

users = { name : user(name) for name in myString.split() }
Run Code Online (Sandbox Code Playgroud)