2015-10-16 75 views
-1

我從文件行這樣寫着:如何通過迭代字符串在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

回答

6

您不能在賦值的左側添加一個添加項(您不能以這種方式構造變形名稱)。您應該使用字典和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