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

478次阅读
没有评论
Python中的元类是什么?如何快速掌握元类

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

 

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

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

</pre>
 

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

在Python3中语法改变了一下:

 

class Simple1(object, metaclass=something…):
[…]
<pre class="brush:js;toolbar:false">

 

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

 

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

</pre>
 

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

 

In : h = New_Hello(lambda x: x)
In : h.func(10), h.hello()
hello world
Out: (10, None)
<pre class="brush:js;toolbar:false">

 

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

 

以上就是Python中元类的详解。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-05发表,共计705字。
新手QQ群:570568346,欢迎进群讨论 Python51学习