通过字符串引用类名? [英] Referring to class names through strings?
问题描述
笔记本电脑
17dell,重量:12磅
桌面$ b b 24hp
我事先知道文本中可能存在哪些实体,应该有。在这个例子中,我已经有类笔记本电脑和桌面定义(可能是类计算机的子类)。解析器只需要创建对象laptop('dell',17,12)和dekstop('hp',24)。
我需要从字符串中检索类名,并创建这些类的对象。是否是邪恶的做事方式?如果是这样,什么是最好的方法(使用Python 3.1)?
如果类在 computers.py
中定义,比方说,你可以
import computers
getattr(computers,Laptop)(< params>)
以实例化 computers.Laptop
。如果它们在您运行代码的同一文件中定义(以便它们是全局变量),则可以执行
globals()[Laptop]
或者,如果你想要一个更强大的映射(例如你想要Nettop,Lapbook和笔记本电脑所有实例化笔记本电脑
),你可以维护一个映射的字符串到其相应的构造函数,并使用:
mapping = {Laptop:Laptop,Nettop:Laptop,...}
映射[Laptop]()
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. Example of the text:
laptop
17" dell, weight: 12 lb
desktop
24" hp
I know in advance which entities may exist in the text, and what attributes they are supposed to have. In this example, I would already have classes laptop and desktop defined (probably subclasses of class computer). The parser would just need to create objects laptop('dell', 17, 12), and dekstop('hp', 24).
If I follow this route, I would need to retrieve class names from strings, and create objects of those classes. Is it the Pythonic way of doing things? If so, what's the best approach (using Python 3.1)? If not, what should I do instead?
Thanks!
What
If the classes are defined in computers.py
, say, you can do
import computers
getattr( computers, "Laptop" )( <params> )
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" ]()
这篇关于通过字符串引用类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!