问题描述
我最近在python中发现了元类.
I recently discovered metaclasses in python.
基本上,python中的元类是创建类的类.有许多有用的原因使您想要执行此操作-例如,任何类型的类初始化.在工厂上注册类,复杂的属性验证,更改继承的方式等.所有这些不仅变得可能而且变得简单.
Basically a metaclass in python is a class that creates a class. There are many useful reasons why you would want to do this - any kind of class initialisation for example. Registering classes on factories, complex validation of attributes, altering how inheritance works, etc. All of this becomes not only possible but simple.
但是在python中,元类也是普通类.因此,我开始怀疑抽象是否可以有用地提高,在我看来它可以并且可以做到:
But in python, metaclasses are also plain classes. So, I started wondering if the abstraction could usefully go higher, and it seems to me that it can and that:
- 元类对应于或实现模式中的角色(如GOF模式语言中一样).
- 元元类是模式本身(如果我们允许它创建代表抽象角色的类的元组,而不仅仅是单个类)
- meta-meta-metaclass是一个 pattern factory ,它对应于GOF模式分组,例如创造,结构,行为.一个工厂,您可以在其中描述某种类型的问题的情况,并为您提供解决问题的一组类.
- meta-meta-meta-metaclass(据我所知)是 pattern factory factory ,这是一个您可以描述问题类型的工厂,它将给出您要询问的图案工厂.
- a metaclass corresponds to or implements a role in a pattern (as in GOF pattern languages).
- a meta-metaclass is the pattern itself (if we allow it to create tuples of classes representing abstract roles, rather than just a single class)
- a meta-meta-metaclass is a pattern factory, which corresponds to the GOF pattern groupings, e.g. Creational, Structural, Behavioural. A factory where you could describe a case of a certain type of problem and it would give you a set of classes that solved it.
- a meta-meta-meta-metaclass (as far as I could go), is a pattern factory factory, a factory to which you could perhaps describe the type of your problem and it would give you a pattern factory to ask.
我在网上找到了一些有关此方面的信息,但大多数情况不是很有用.一个问题是,不同的语言对元类的定义略有不同.
I have found some stuff about this online, but mostly not very useful. One problem is that different languages define metaclasses slightly differently.
还有没有其他人在python/elsewhere中使用过像这样的元类,或者在野外使用过它,还是考虑过?其他语言的类似物是什么?例如.在C ++中,模板递归能走多深?
Has anyone else used metaclasses like this in python/elsewhere, or seen this used in the wild, or thought about it? What are the analogues in other languages? E.g. in C++ how deep can the template recursion go?
我非常想对其进行进一步的研究.
I'd very much like to research it further.
推荐答案
Smalltalk中的类系统是一个有趣的研究对象.在Smalltalk中,一切都是对象,每个对象都有一个类.这并不意味着层次结构会达到无穷大.如果我没记错的话,它会像这样:
The class system in Smalltalk is an interesting one to study. In Smalltalk, everything is an object and every object has a class. This doesn't imply that the hierarchy goes to infinity. If I remember correctly, it goes something like:
5->整数->整数类->元类->元类类->元类-> ...(循环)
5 -> Integer -> Integer class -> Metaclass -> Metaclass class -> Metaclass -> ... (it loops)
其中'->'表示是"的一个实例.
Where '->' denotes "is an instance of".
这篇关于是否有人在使用Python/其他语言的meta-meta-classes/meta-meta-meta-classs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!