6

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?

2 Answers 2

5

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]

Sign up to request clarification or add additional context in comments.

4 Comments

It worked! But now these instances won't be attached to any variable? Lets say that I create a new function in this class: def age_increment(self): self.age =+ 1 The notation that i've learned, if you have declared a instance like this: bob = person(name='bob', age=23, job='professor') To use the function you would have to: bob.age_increment() How do I do this now?
Just use list accessor methods, e.g. to impcrement the age of the first person in the list, people[0].increment_age()
You would need to access the objects from the List. The problem here would be determining which element in the list corresponds to the person you want to update. For this you could use a dictionary instead of a List. I've updated my answer to show how to do this.
Thanks!! It helped a lot!
1

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.

1 Comment

Very concise :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.