I need to parse some text file, create objects for various entities encountered in the text, and put them in some data structure (e.g., a list) for further processing. Examp
If the classes are defined in computers.py
, say, you can do
import computers
getattr( computers, "Laptop" )( )
to instantiate a computers.Laptop
. If they are defined in the same file that you are running the code in (so that they are global variables), you can do
globals()[ "Laptop" ]
but this is less elegant; it would be nicer to put them in a separate scope.
Alternatively, if you want a more powerful mapping (say you want "Nettop", "Lapbook", and "Laptop" all to instantiate Laptop
), you could maintain a mapping of strings to their corresponding constructor and use that:
mapping = { "Laptop": Laptop, "Nettop": Laptop, ... }
mapping[ "Laptop" ]()