将类属性反向映射到Python中的类

编程入门 行业动态 更新时间:2024-10-28 21:20:14
本文介绍了将类属性反向映射到Python中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在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中的类

本文发布于:2023-11-17 05:43:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609033.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类属   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!