How to return new Object every time by calling same dict value in Python?

Viewed 217

I am trying to set class definition for dictionary element that every time by getting dict element new object should appear.

Example:

types = {}
types[first_type] = FirstType()
types[second_type] = SecondType()

And by setting types[first_type] I have to get new FirstType():

some_var = new types[first_type] # this is illegal statement.

How can I achieve this in Python?

2 Answers

Try making them into "object generators" themselves.

types = {}
types[first_type] = FirstType
types[second_type] = SecondType

Then you can get a new object each time by calling that that point.

some_var = types[first_type]()

Here's a working example with standard types:

>>> types = {"list": list, "int": int, "dict": dict}
>>> types["list"]()
[]
>>> types["int"]()
0
Related