Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to dynamically create class instances?

I don't know how many class instances I will have from the get-go, so I need to create them dynamically, but I would also like to keep the code tidy and readable.

I was thinking of doing something like this:

names = ['Jon','Bob','Mary']

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

people = {}
for name in names:
    people[name] = Person(name)

It works, but I can't seem to find any examples of people doing this online (though I didn't look much). Is there any reason I should avoid doing this? If so, why and what is a better alternative?

like image 989
TimY Avatar asked Jan 16 '23 10:01

TimY


1 Answers

If you want to create class instances dynamically, which is exactly what you are doing in your code, then I think your solution looks perfectly fine and is a pythonic way to do so (although I have to say there are of course other ways). Just to give you some food for thought: you could register/store each new instance with the class like that:

class Person():
    people={}
    @classmethod
    def create(cls,name):
        person=Person(name)
        cls.people[name]=person
        return person
    def __init__(self, name):
        self.name = name

And if you are getting adventerous, you can try the same with metaclass, but I will leave that for your research :-)

like image 146
schacki Avatar answered Jan 23 '23 00:01

schacki