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

问题描述:

我从文件行这样写着:如何通过迭代字符串在Python中创建对象?

a b c d e f 

有了这个字符串,我希望把每个字母变成我的用户类新的“用户”。所以,我想是这样的:

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

换句话说,我希望像“用户A =用户(” A“)”,其中用户是我定义采取一个字符串作为参数类。

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

+0

你可能想A =用户( 'A'),B =用户('b')? ... – garg10may

+0

所以你想要一组变量usera ='a'等。这可以使用'eval'完成,但我会质疑有用性。只需使用一个字典,其中user ['a'] = User('a')' – RobertB

+0

是的。正如发布的答案所示,我会考虑使用字典。 – AlwaysQuestioning

您不能在赋值的左侧添加一个添加项(您不能以这种方式构造变形名称)。您应该使用字典和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() } 
+0

初始字符串是myFile = open('file.txt。)的结果,然后是myFilfe = myFile.readline()。我在myFile上使用split时遇到了问题。 – AlwaysQuestioning

+0

你有什么麻烦?你不应该做myFilfe = myFile.readline(),因为你放弃了文件对象,这有点淘气。明确关闭 –

+0

'accessControls = open('access.txt','r') usersString = accessControls.readline(); 用户= {} 用户名在accessControls.split(): 用户[用户名] =用户(名称)' 我的错误是:AttributeError的: '文件' 对象没有属性在 '分裂' – AlwaysQuestioning