Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create instances of a class python

Tags:

python

oop

class

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?

like image 367
Rodrigo Avatar asked Aug 06 '15 03:08

Rodrigo


People also ask

How do you create an instance of a class dynamically in Python?

Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

How do you create an instance of a class in Python?

To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.

How do I create a dynamic instance?

You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them.

How do I create a dynamic code in Python?

Method 1: exec() The exec() function can take any source code as a string and run it within your script. It's the perfect way to dynamically create a function in Python! ? Python's built-in exec() executes the Python code you pass as a string or executable object argument.


1 Answers

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]

like image 119
rfj001 Avatar answered Oct 02 '22 12:10

rfj001