{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 元类\n",
    "\n",
    "**元类** 用于创建和管理类（`class`）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Foo: ...\n",
    "\n",
    "isinstance(Foo, object)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`Foo` 是由 {class}`type` 创建的："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "type"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(Foo)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{note}\n",
    "使用 `class` 语句创建新类：\n",
    "\n",
    "1. 类主体将作为其私有字典内的一系列语句执行。\n",
    "2. 类内语句的执行过程与正常代码执行过程相同，只是增加了会在私有成员（名称以 `__` 开头）上发生的名称变形。\n",
    "3. 类的名称、基类类别和字典将传递给元类的构造函数，以构建相应的类对象。\n",
    "```\n",
    "\n",
    "- 可以显式地指定元类：\n",
    "\n",
    "    ```python\n",
    "    class Foo(metaclass=type): ...\n",
    "    ```\n",
    "\n",
    "- 如果没有显式指定元类，`class` 语句将检查基类元组（如果存在）中的第一项。\n",
    "- 如果没有指定基类，`class` 语句将检查全局变量 `__metaclass__` 是否存在。比如：\n",
    "\n",
    "    ```python\n",
    "    __metaclass__ = type\n",
    "    class Foo: ...\n",
    "    ```\n",
    "\n",
    "在 Python3 中默认元类是 `type`。"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "879d2452f9c79bf336c55e4e9b753d3a7aba25fc5112fa785acaf27b9e7e29e7"
  },
  "kernelspec": {
   "display_name": "Python 3.10.0 64-bit (conda)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.0"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
