我在Python中有一些代码,其中将有一堆类,每个类都有一个属性_internal_attribute.我希望能够生成这些属性到原始类的映射.本质上,我希望能够做到这一点:
I have some code in Python where I'll have a bunch of classes, each of which will have an attribute _internal_attribute. I would like to be able to generate a mapping of those attributes to the original class. Essentially I would like to be able to do this:
class A(object): _internal_attribute = 'A attribute' class B(object): _internal_attribute = 'B attribute' a_instance = magic_reverse_mapping['A attribute']() b_instance = magic_reverse_mapping['B attribute']()我在这里缺少的是如何生成magic_reverse_mapping字典.我有一种直觉,认为让一个元类生成A和B是解决此问题的正确方法.看起来正确吗?
What I'm missing here is how to generate magic_reverse_mapping dict. I have a gut feeling that having a metaclass generate A and B is the correct way to go about this; does that seem right?
推荐答案您可以使用元类在magic_reverse_mapping中自动注册您的类:
You can use a meta class to automatically register your classes in magic_reverse_mapping:
magic_reverse_mapping = {} class MagicRegister(type): def __new__(meta, name, bases, dict): cls = type.__new__(meta, name, bases, dict) magic_reverse_mapping[dict['_internal_attribute']] = cls return cls class A(object): __metaclass__ = MagicRegister _internal_attribute = 'A attribute' afoo = magic_reverse_mapping['A attribute']()或者,您可以在类上使用装饰器进行注册.我认为这更具可读性,更容易理解:
Alternatively you can use a decorator on your classes to register them. I think this is more readable and easier to understand:
magic_reverse_mapping = {} def magic_register(cls): magic_reverse_mapping[cls._internal_attribute] = cls return cls @magic_register class A(object): _internal_attribute = 'A attribute' afoo = magic_reverse_mapping['A attribute']()或者您甚至可以手工完成.不使用任何魔法就没那么多工作了:
Or you could even do it by hand. It's not that much more work without using any magic:
reverse_mapping = {} class A(object): _internal_attribute = 'A attribute' reverse_mapping[A._internal_attribute] = A看看不同的变体,我认为装饰器版本将是最令人愉悦的.
Looking at the different variants I think the decorator version would be the most pleasant to use.
更多推荐
将类属性反向映射到Python中的类
发布评论