我有几个“model”类(ModelFoo、ModelBar、ModelBaz、ModelQux),它们可以由具有不同标识符的客户机实例化。为了将标识符映射到正确的模型类,我创建了一个映射类:
class ModelTypes(object):
""" Enumeration of supported class types, mapping userland identifier to constructor.
"""
# Multiple names per model type enable us to run several instances in parallel
FooModel = ModelFoo
fooMod = ModelFoo
foo = Foo
ff = Foo
Bar = ModelBar
bar = ModelBar
Baz = ModelBaz
baz = ModelBaz
Qux = ModelQux
qux = ModelQux
@classmethod
def getTypes(cls):
""" Return the names of the attributes explicitly defined above.
"""
for attrName in dir(cls):
attrValue = getattr(cls, attrName)
if (isinstance(attrValue, type) and
issubclass(attrValue, acceptableClassImplementations)):
yield attrName # attrName is an acceptable model name
也就是说,我使用ModelTypes
类进行反向查找,其中我需要将一个简单标识符(例如qux
)映射回相应的类(ModelQux
)。但是添加客户机可能使用的所有标识符会变得单调乏味。是否有标准/建议的方法将关键字映射到类?你知道吗
如果您只想少写将多个变量定义为同一个值的代码,那么可以使用以下语法:
所以你可以:
但是如果您想要更自动化的东西,那么您需要一个
dict
,它是唯一的内置映射对象,但是它可以实现为以与项相同的方式响应属性:同样,
dict
的任何子类都可以定义一个__missing__
方法,如果您试图获取一个不存在的键,则会调用该方法,因此您可以实现它来再次检查dict,忽略大小写并检查类的文档名:然后,您可以定义一个与一个类相对应的名称,并将处理所有变体:
相关问题 更多 >
编程相关推荐