Hi,

I have a question regard to assign the values to each memebrs of the class objects because I have a large list of class objects. Can I do the following? If not, how can I achieve the same thing? Thanks in advance.

class person():
def __init__(self):
self.name = ' '
self.job = ' '
self.age = 0

# define a list of class objects
personList = []

personList[0].name = 'abc'
personList[0].job = 'worker'
personList[0].age = 20
personList[1].name = 'efg'
personList[1].job = 'student'
personList[1].age = 22
personList[2].name = 'hlk'
personList[2].job = 'doctor'
personList[2].age = 25

Well, wrap your posts in (code = Python) (/code) tags for greater clarity.

My favorite way to do this would be to pull the information out of tuples like this:

class person():
    def __init__(self):
        self.name = ' '
        self.job = ' '
        self.age = 0

people = [('abc','worker',20),
          ('efg', 'student',22),
          ('hlk', 'doctor', 25)]  # yeah, right!

personList = []

for name,job,age in people:  # this unpacks each tuple in the list.
    tmp = person()
    tmp.name = name
    tmp.job = job
    tmp.age = age
    personList.append(tmp)

Now, if you're willing to modify the __init__ a bit, then you can write even cleaner code:

class person():
    def __init__(self,name='',job='',age=0):
        self.name = name
        self.job = job
        self.age = age

people = [('abc','worker',20),
          ('efg', 'student',22),
          ('hlk', 'doctor', 25)]  # yeah, right!

personList = []

for name,job,age in people:
    personList.append(Person(name,job,age))

Jeff

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Hi, Jeff,

That's the nice code. Thanks so much.
But my problem is that I have thousands people of a large list of class objects to assign the values with about 30 attributes in the class. I can not manually do that.
each attributes is in a list. How can I combine 30 attributes into a tuple as you mentioned above so that I loop through thousands of people?

Thanks again.

Edited 3 Years Ago by happygeek: fixed formatting

What does a typical element in your list look like?
If it's a file, what does a typical data line look like?

How can I combine 30 attributes into a tuple as you mentioned above so that I loop through thousands of people?

You don't have to use a tuple. That was just a convenient container for the example presented above. As vegaseat already stated, a little more info would be helpful. Give a few examples of input and what it should look like on output. It you take this from a file, and that from a list, etc. be sure to mention that. This should be fairly simple to do with python.

This question has already been answered. Start a new discussion instead.