Python元类MetaClass

作者: 戏之地 | 来源:发表于2016-12-21 15:55 被阅读201次

上文Python中object和type的关系中我们提到元类的概念。type就是最大的一个元类。在这里,我们详细介绍一下元类。
下图中,第一列中的对象,我们称之为元类

Type,TypeObject,instance

创建一个元类

#!/usr/bin/env python
# -*- coding:utf-8 -*-


class M(type):
    # 定义了一个元素,位于第一列
    pass


print(M.__class__)
print(M.__bases__)


class CM(object, metaclass=M):
    # 定义了一个元素,位于第二列
    pass


print(CM.__class__)
print(CM.__bases__)

# my_cm位于第三列
my_cm = CM()


print(my_cm.__class__)

输出结果:

D:\Python\python.exe E:/工程/Python/元类.py
<class 'type'>
(<class 'type'>,)
<class '__main__.M'>
(<class 'object'>,)
<class '__main__.CM'>

利用type动态创建类

上面只是浮光掠影,在介绍元类的使用之前,先掌握type动态创建类的方法
因为Python是动态语言,所以可以动态


def print_hello(self, s):
    # 这相当于类中定义的方法属性,第一个参数须为self
    print("hello %s " % s)
    
    
def __init__(self,name,age):
    self.name = name
    self.age = age

Hello = type("Hello", (object,), dict(f=print_hello, f2=print,num = 1,__init__=__init__))

print(Hello("jatrix",14).__dict__)
print(Hello.__dict__)

输出

{'name': 'jatrix', 'age': 14}
{'num': 1, 'f': <function print_hello at 0x010A5660>, '__doc__': None, '__dict__': <attribute '__dict__' of 'Hello' objects>, '__init__': <function __init__ at 0x0185E420>, 'f2': <built-in function print>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Hello' objects>}

我们在什么情况下使用元类呢

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319106919344c4ef8b1e04c48778bb45796e0335839000
http://blog.csdn.net/psh2009/article/details/10330747
http://blog.csdn.net/igorzhang/article/details/39026885
http://www.cnblogs.com/Security-Darren/p/4094959.html
http://blog.csdn.net/igorzhang/article/details/39026885
http://www.cnblogs.com/Security-Darren/p/4094959.html
http://blog.csdn.net/u012005313/article/details/50111455
https://docs.python.org/3.5/howto/argparse.html
http://blog.csdn.net/Shiroh_ms08/article/details/52848049?locationNum=9&fps=1

相关文章

  • 面试常考(python)

    Python语言特性 1.Python的函数参数传递 2.元类 metaclass metaclass 允许创建类...

  • metaclass

    深刻理解Python中的元类(metaclass) - 文章 - 伯乐在线

  • interview_python

    Python语言特性1 Python的函数参数传递2 Python中的元类(metaclass)3 @static...

  • Python元类metaclass

    最近接触到一个对xml进行序列化的python库,实际上可以理解为一个小的ORM,只不过数据的来源是xml而不是数...

  • Python元类MetaClass

    上文Python中object和type的关系中我们提到元类的概念。type就是最大的一个元类。在这里,我们详细介...

  • Python: 陌生的 metaclass

    原文出处: geekvi 元类 Python 中的元类(metaclass)是一个深度魔法,平时我们可能比较少接触...

  • 理解Python中的元类(metaclass)

    理解Python中的元类(metaclass) 这篇文章基本上是What are metaclasses in P...

  • python基础 -- 元类metaclass

    1. 作用 暂时不深究 2. 操作

  • python:metaclass

    metaclass翻译过来应该是元类的意思。python中一切皆是对象,连类也是对象 而类是元类的实例,默认的cl...

  • Python中的metaclass

    之前一直被Python中的元类困扰,花了点时间去了解metaclass,并记录下我对于元类的理解,这里使用的是Py...

网友评论

    本文标题:Python元类MetaClass

    本文链接:https://www.haomeiwen.com/subject/scmqvttx.html