栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

作为一个的程序单元,学习编程的人应该都需要掌握。今天小编为大家带来元类的讲解。


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

class Foo(object):
   __metaclass__ = something...
   [...]


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

在Python3中语法改变了一下:


class Simple1(object, metaclass=something...):
   [...]


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


class Hellometa(type):
   def __new__(cls, name, bases, attrs):
       def __init__(cls, func):
           cls.func = func
       def hello(cls):
           print 'hello world'
       t = type.__new__(cls, name, bases, attrs)
       t.__init__ = __init__
       t.hello = hello
       return t
       class New_Hello(object):
   __metaclass__ = Hellometa


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


In : h = New_Hello(lambda x: x)
In : h.func(10), h.hello()
hello world
Out: (10, None)


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


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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/12438.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号