• 技术文章 >Python技术 >Python基础教程

    Python中的元类是什么?如何快速掌握?

    2020-11-05 17:47:31原创2138
    作为一个的程序单元,学习编程的人应该都需要掌握。今天小编为大家带来元类的讲解。


    Python2创建类的时候,可以添加一个__metaclass__属性:

    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;">class Foo(object):<br>    __metaclass__ = something...<br>    [...]<br></span></p>


    如果你这样做,Python会使用元类来创建Foo这个类。Python会在类定义中寻找__metaclass__。如果找到它,Python会用它来创建对象类Foo。如果没有找到它,Python将使用type来创建这个类。

    在Python3中语法改变了一下:


    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;">class Simple1(object, metaclass=something...):<br>    [...]<br></span></p>


    本质上是一样的。拿一个元类例子分享一下:


    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;">class HelloMeta(type):<br>    def __new__(cls, name, bases, attrs):<br>        def __init__(cls, func):<br>            cls.func = func<br>        def hello(cls):<br>            print 'hello world'<br>        t = type.__new__(cls, name, bases, attrs)<br>        t.__init__ = __init__<br>        t.hello = hello<br>        return t<br>        class New_Hello(object):<br>    __metaclass__ = HelloMeta<br></span></p>


    New_Hello初始化需要添加一个参数,并包含一个叫做hello的方法:


    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;">In : h = New_Hello(lambda x: x)<br>In : h.func(10), h.hello()<br>hello world<br>Out: (10, None)<br></span></p>


    PS: 这个例子只能运行于Python2。


    以上就是Python中元类的详解。更多Python学习推荐:PyThon学习网教学中心

    专题推荐:python元类
    上一篇:Python Socket是什么?怎么用? 下一篇:如何快速掌握python中的yield from语法?

    相关文章推荐

    • 详解Python元类(metaclass)

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网