Rodrigo
Rodrigo

Reputation: 137

Dynamically create instances of a class python

I'm new in python and I'm trying to dynamically create new instances in a class. So let me give you an example, if I have a class like this:

class Person(object):
    def __init__(self, name, age, job):
        self.name = name
        self.age = age
        self.job = job

As far as I know, for each new instance I have to insert, I would have to declare a variable and attach it to the person object, something like this:

variable = Person(name, age, job)

Is there a way in which I can dynamically do this? Lets suppose that I have a dictionary like this:

persons_database = {
'id' : ['name', age, 'job'], .....
}

Can I create a piece of code that can iterate over this db and automatically create new instances in the Person class?

Upvotes: 6

Views: 8538

Answers (2)

rfj001
rfj001

Reputation: 8508

Just iterate over the dictionary using a for loop.

people = []
for id in persons_database:
    info = persons_database[id]
    people.append(Person(info[0], info[1], info[2]))

Then the List people will have Person objects with the data from your persons_database dictionary

If you need to get the Person object from the original id you can use a dictionary to store the Person objects and can quickly find the correct Person.

people = {}
for id, data in persons_database.items():
    people[id] = Person(data[0], data[1], data[2])

Then you can get the person you want from his/her id by doing people[id]. So to increment a person with id = 1's age you would do people[1].increment_age()

------ Slightly more advanced material below ----------------

Some people have mentioned using list/dictionary comprehensions to achieve what you want. Comprehensions would be slightly more efficient and more pythonic, but a little more difficult to understand if you are new to programming/python

As a dictionary comprehension the second piece of code would be people = {id: Person(*data) for id, data in persons_database.items()}

And just so nothing here goes unexplained... The * before a List in python unpacks the List as separate items in the sequential order of the list, so for a List l of length n, *l would evaluate to l[0], l[1], ... , l[n-2], l[n-1]

Upvotes: 5

lemonhead
lemonhead

Reputation: 5518

Sure, a simple list comprehension should do the trick:

people = [Person(*persons_database[pid]) for pid in persons_database]

This just loops through each key (id) in the person database and creates a person instance by passing through the list of attributes for that id directly as args to the Person() constructor.

Upvotes: 1

Related Questions