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?
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With