简体   繁体   中英

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.

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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