`
huangyiiiiii
  • 浏览: 116217 次
  • 性别: Icon_minigender_1
最近访客 更多访客>>
社区版块
存档分类
最新评论

metaclass in python (part 2)

阅读更多
接着上一篇的讲。

现在我们知道了,metaclass 生 class,class 生 instance。
但是 metaclass 还可以有它的 metametaclass,metametaclass 还可以有... 如果反复,永无止境。这样想起来,脑袋就有点晕了。
其实在 python 中万物皆对象而已,所有对象皆有其类型,对象的类型也还是对象!而类型对象的类型就是它自己。
而前面说过的所谓 instance、class、metaclass 等东西,都只是不同种类的对象而已。

判断对象是什么对象的唯一方法就是通过其提供的“接口”,这就是所谓的 duck type!只要一个对象实现了成为一个 class 所需的接口,它就是 class !metaclass 亦然。
那么我们不如先来讨论讨论 metaclass 的接口吧,看看究竟需要实现哪些接口能使一个对象成为一个 metaclass。
先来看一些等价关系:
class Temp(object):
__metaclass__ = Meta
a = 1
def __init__(self, a):
self.a = a
上面代码其实等价于:
Temp = Meta('Temp', (object,),
{'a':1, '__module__':'current module name', '__metaclass__':the object Meta, '__init__':function object __init__})
(class的语法原来只是个语法糖而已,汗!)
由此可见 Meta 首先应该是个 callable,并且应该接受如上所示的三个参数。
t = Temp(2) # 构建 Temp 的 instance
从这一句我们可以看出 Temp 也应该是个 callable 对象。
而我们知道 Temp 对象其实是调用 Meta 所返回的,也就是说 Meta 这个 callable 对象返回的还应该是一个 callable 对象。
典型地,如果 Meta 是一个 class,意味着它应该实现一个 __call__ 方法。这样的话,那么上面那句就可以等价为:
t = Temp.__call__(2)
上面说的这几点基本上可以作为判断一个对象能否成为 metaclass 的标准了:一个接受三个参数并返回另一个 callable 对象的 callable 对象!

不急,在继续分析之前我们不妨利用刚才发现的这一点搞点小怪先,呵呵。
def Meta(name, bases, attrs):
def _class(a):
return a
return _class

class Temp(object):
'''
>>> Temp(1)
1
>>> Temp('hello')
'hello'
'''
__metaclass__ = Meta
继续分析,虽然可以像上面那样恶搞,不过要想写个有点实际用处的 metaclass ,还是通过 class 来实现比较方便。
最典型的方法便是直接继承 type 了,毕竟那是所有 new-style class 的 metaclass,在 python3000 里就要成为所有 class 默认的 metaclass 了。
可以说大部分 metaclass 的实现都是这么做的,不过下面要分析的这一例却是个例外,虽然不像上面我们写的那个 metaclass 那么奇怪,不过分析起来也不是那么容易的。

不过我们还需要继续澄清一些事实,先看这个例子:
class Temp(object):
@staticmethod # 这一句可以忽略,不管有没有这句,__new__ 都是静态方法
def __new__(cls, a):
return object.__new__(cls, a)
def __init__(self, a):
self.a = a
def __getattribute__(self, name):
return super(Temp, self).__getattribute__(name)
def __getattr__(self, name):
return super(Temp, self).__getattr__(name)

t = Temp(2)
print t.a
在默认的 metaclass type 的实现中,上面这句,也就是 type 的 __call__ 方法,其实是分以下两步完成的:
t = Temp.__new__(Temp, 2) # 调用 staticmethod __new__,创建 instance
t.__init__(2) # 调用该 instance 的构造函数,初始化 instance
另外,既然 Temp 实现了 __getattribute__, t.a 实际上等价于:
try:
t.__getattribute__(self, 'a')
except AttributeError:
t.__getattr__(self, 'a')
到这里基本上一些概念问题已经搞清楚了,下一篇终于可以正式开始研究这里的代码了。

参考:
Unifying types and classes in Python 2.2 这是老大对 python2.2 以后的“python对象模型”的深刻的描述
The Python 2.3 Mehod Resolution Order 这也是今天碰巧看到的好文,虽然与本文没有什么联系,不过,此文深入讲解了 python2.3 以后对多继承的实现, 我也是看完这篇才知道实现个多继承是如此的复杂,不过幸好他们找到了合适的算法。 另外对于平时不经常接触算法的人(比如我)来说,偶尔用数学的思维思考思考还有很有好处的。
New-style Classes 这里是 new-style class 相关的文献的集合。
另外想找这方面中文资料的兄弟可以去啄木鸟:python中的新型类及其实例详解 Metaclasses(元类)
分享到:
评论

相关推荐

    python中metaclass原理与用法详解

    本文实例讲述了python中metaclass原理与用法。分享给大家供大家参考,具体如下: 什么是 metaclass. metaclass (元类)就是用来创建类的类。在前面一篇文章《python动态创建类》里我们提到过,可以用如下的一个观点来...

    python-metaclass.py

    python-metaclass.py

    Hands-On Meta Learning with Python.epub

    Meta learning using one-shot learning, MAML, Reptile, and Meta-SGD with TensorFlow

    Python库 | metaclass-1.0-py2.py3-none-any.whl

    python库。 资源全名:metaclass-1.0-py2.py3-none-any.whl

    Python使用metaclass实现Singleton模式的方法

    主要介绍了Python使用metaclass实现Singleton模式的方法,实例分析了Python基于metaclass实现单例模式的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下

    深入理解Python中的元类(metaclass)

    提问者自称已经掌握了有关Python OOP编程中的各种概念,但始终觉得元类(metaclass)难以理解。他知道这肯定和自省有关,但仍然觉得不太明白,希望大家可以给出一些实际的例子和代码片段以帮助理解,以及在什么情况下...

    举例讲解Python中metaclass元类的创建与使用

    在Python中我们用type函数可以动态地创建一个元类,同样也可以用__metaclass__属性来指定一个元类,接下来我们就来具体举例讲解Python中metaclass元类的创建与使用

    详解python单例模式与metaclass

    主要介绍了python单例模式与metaclass,文章介绍了单例模式的实现方式

    Python 中 Meta Classes详解

    首先,在认识metaclass之前,你需要认识下python中的class。python中class的奇怪特性借鉴了smalltalk语言。大多数语言中,classes仅仅是用于描述怎样创建一个对象的代码端。在某种程度上说,python中的class也是这样...

    Pro Python 2nd edition 英文pdf

    Pro Python 第2版,2014.12.17出版的新书 You’ve learned the basics of Python, but how do you take your skills to the next stage? Even if you know enough to be productive, there are a number of ...

    Python库 | meta_ml-0.0.16-py3-none-any.whl

    资源分类:Python库 所属语言:Python 资源全名:meta_ml-0.0.16-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    Python探索之Metaclass初步了解

    本文先简单介绍了Python中的类,然后是主要内容,涉及Metaclass的相关内容,还是不错的,这里分享给大家,供需要的朋友参考。

    Python库 | aliyun-python-sdk-nls-cloud-meta-1.0.0.tar.gz

    python库。 资源全名:aliyun-python-sdk-nls-cloud-meta-1.0.0.tar.gz

    Python-实现MetaRLA3C算法

    实现Meta-RL A3C算法

    详解python metaclass(元类)

    主要介绍了python metaclass(元类)的相关资料,帮助大家更好的理解和学习,感兴趣的朋友可以了解下

    Python Cookbook, 2nd Edition

    Interpolating Variables in a Stringin Python 2.4 Recipe 1.18. Replacing Multiple Patterns in a Single Pass Recipe 1.19. Checking a String for Any of Multiple Endings Recipe 1.20. Handling ...

    Meta:Python元编程

    例子这显示了如何将python源代码带到代码对象并从python内部再次返回: import meta , astsource = '''a = 1b = 2c = (a ** b)'''mod = ast . parse ( source , '<nofile>' , 'exec' )code = compile ( mod , '...

Global site tag (gtag.js) - Google Analytics