python类的factory+注册表模式。
class-registr的Python项目详细描述
类注册表
在注册表模式和工厂模式的交叉点上有 ClassRegistry:
- 定义基于 可配置钥匙。
- 无缝地创建强大的服务注册中心。
- 与setuptools的entry_points系统集成以创建注册表 可由第三方库无限扩展!
- 还有更多!
开始
使用class_registry.ClassRegistry类创建注册表,然后 用它的register方法装饰要注册的任何类:
fromclass_registryimportClassRegistrypokedex=ClassRegistry()@pokedex.register('fire')classCharizard(Pokemon):...@pokedex.register('grass')classBulbasaur(Pokemon):...@pokedex.register('water')classSquirtle(Pokemon):...
要从注册表创建类实例,请使用下标运算符:
# Charizard, I choose you!fighter1=pokedex['fire']# CHARIZARD fainted!# How come my rival always picks the type that my pokémon is weak against??fighter2=pokedex['grass']
高级用法
ClassRegistry还有很多功能,包括:
- 为新的类实例提供args和kwargs。
- 自动注册非抽象类。
- 与setuptools的entry_points系统集成,以便第三方 库可以将它们自己的类添加到注册表中。
- 在实例缓存中包装注册表以创建服务注册表。
- 还有更多!
要求
ClassRegistry与Python3.6、3.5和2.7版本兼容。
安装
通过pip安装最新的稳定版本:
pip install class-registry