Referring to class names through strings?

后端 未结 5 1098
面向向阳花
面向向阳花 2021-01-16 17:32

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

5条回答
  •  时光取名叫无心
    2021-01-16 18:13

    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" ]()
    

提交回复
热议问题