简体   繁体   English

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

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

I read in a line from a file as such: 我从这样的文件中读取一行:

a b c d e f

With this string, I want to turn each letter into a new "user" in my user class. 有了这个字符串,我想在用户类中将每个字母变成一个新的“用户”。 So what I want is something like: 所以我想要的是这样的:

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

In other words, I would want something like "userA = user("a")", where user is a class I defined to take in a string as a parameter. 换句话说,我想要“ userA = user(“ a”)”之类的东西,其中user是我定义为接收字符串作为参数的类。

I'm having a hard time finding ways to iterate strings in Python with regard to a file, and then using the result to create an object. 我很难找到一种方法来迭代Python中关于文件的字符串,然后使用结果创建对象。

You can't have an addition on the left hand side of an assignment (you cannot construct variale names that way). 您不能在作业的左侧添加任何内容(您不能以这种方式构造变量名称)。 You should use a dictionary and the str.split method: 您应该使用字典和str.split方法:

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

You can also use a dictionary comprehension to achieve the same: 您还可以使用字典理解来实现相同目的:

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

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

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