是否有一种方法来创建子类? [英] Is there a way to create subclasses on-the-fly?
问题描述
我正在创建一个游戏,其中我有一个复杂的方法来创建实体。
I'm creating a game in which I have a somewhat complex method for creating entities.
加载一个级别时,加载代码读取一堆YAML包含所有不同可能单元的属性的文件。使用YAML文件,它创建一个所谓的 EntityResource
对象。此EntityResource对象在生成新单元时充当信息的权威来源。目标是双重的:
When a level is loaded, the loading code reads a bunch of YAML files that contain attributes of all the different possible units. Using the YAML file, it creates a so-called EntityResource
object. This EntityResource object serves as the authoritative source of information when spawning new units. The goal is twofold:
- 通过对YAML文件的输出执行散列检查来阻止欺骗
<
这些 EntityResource
对象然后被馈送到 EntityFactory
对象中以产生特定类型的单位。
These EntityResource
objects are then fed into an EntityFactory
object to produce units of a specific type.
我的问题如下。有一种方法可以基于读取的YAML文件的内容动态创建 EntityResource
的子框架
My question is as follows. Is there a way to create sublcasses of EntityResource
dynamically, based on the contents of the YAML file being read in?
此外,我希望每个YAML文件派生的子类都被分配一个单例元类。任何注意事项?
Also, I would like each of these YAML-file-derived subclasses to be assigned a singleton metaclass. Any caveats?
推荐答案
我不知道这是否是你要找的,但你可以使用 键入
动态创建子类:
I'm not sure if this is what you're looking for, but you can use type
to create subclasses dynamically:
SubClass = type('SubClass', (EntityResource,), {})
编辑:要了解类型
是如何工作的,您只需要翻译如何编写类并将其转换为键入
调用。例如,如果你想写如下:
To understand how type
works, you just need to translate how would you write the class and translate that into a type
call. For example, if you want to write something like:
class SubClass(EntityResource):
A=1
B=2
那么,将被翻译为:
SubClass = type('SubClass', (EntityResource,), {'A': 1, 'B': 2})
其中:
- 只是类名
- 第二个参数是父类的列表
- 第三个参数是字典初始化类对象。这不仅包括类属性,还包括方法。
这篇关于是否有一种方法来创建子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!