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

如何通过遍历字符串在Python中创建对象?,python,string,object,iteration,character,Python,String,Object,Iteration,Character,我从文件中读到一行内容如下: 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中对一个文

我从文件中读到一行内容如下:

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() }

您可能需要A=user('A')、B=user('B')。。。因此,您需要一组变量usera='a',等等。这可以使用
eval
来完成,但我怀疑其有用性。只需使用dict,其中
user['a']=user('a')
Yes。我将按照发布的答案建议使用dict。初始字符串是myFile=open('file.txt.)的结果,然后是myFilfe=myFile.readline()。在我的文件中使用拆分时遇到问题。您遇到了什么问题?您不应该执行myFilfe=myFile.readline(),因为您松开了file对象,这有点顽皮。最好显式关闭它
accessControls=open('access.txt','r')usersString=accessControls.readline();users={}表示accessControls.split()中的用户名:users[username]=user(name)
我的错误是:AttributeError:'file'对象没有usersString.split()中用户名的属性“split”
Whoops,没错。很抱歉一直打扰您,但现在我发现TypeError:“module”对象不可调用——这与我尝试创建对象的方式有关吗?