1572 lines
276 KiB
HTML
1572 lines
276 KiB
HTML
|
||
<!DOCTYPE html>
|
||
|
||
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
|
||
<head>
|
||
<meta charset="utf-8" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
|
||
|
||
<title>3. 数据模型 — Python 3.8.20 文档</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
|
||
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
|
||
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
|
||
|
||
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
|
||
<script src="../_static/jquery.js"></script>
|
||
<script src="../_static/underscore.js"></script>
|
||
<script src="../_static/doctools.js"></script>
|
||
<script src="../_static/language_data.js"></script>
|
||
<script src="../_static/translations.js"></script>
|
||
|
||
<script src="../_static/sidebar.js"></script>
|
||
|
||
<link rel="search" type="application/opensearchdescription+xml"
|
||
title="在 Python 3.8.20 文档 中搜索"
|
||
href="../_static/opensearch.xml"/>
|
||
<link rel="author" title="关于这些文档" href="../about.html" />
|
||
<link rel="index" title="索引" href="../genindex.html" />
|
||
<link rel="search" title="搜索" href="../search.html" />
|
||
<link rel="copyright" title="版权所有" href="../copyright.html" />
|
||
<link rel="next" title="4. 执行模型" href="executionmodel.html" />
|
||
<link rel="prev" title="2. 词法分析" href="lexical_analysis.html" />
|
||
<link rel="canonical" href="https://docs.python.org/3/reference/datamodel.html" />
|
||
|
||
|
||
|
||
|
||
|
||
<style>
|
||
@media only screen {
|
||
table.full-width-table {
|
||
width: 100%;
|
||
}
|
||
}
|
||
</style>
|
||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||
|
||
</head>
|
||
<body>
|
||
<div class="mobile-nav">
|
||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||
<label for="menuToggler" class="toggler__label">
|
||
<span></span>
|
||
</label>
|
||
<nav class="nav-content" role="navigation">
|
||
<a href="https://www.python.org/" class="nav-logo">
|
||
<img src="../_static/py.svg" alt="Logo"/>
|
||
</a>
|
||
<div class="version_switcher_placeholder"></div>
|
||
<form role="search" class="search" action="../search.html" method="get">
|
||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||
<path fill-rule="nonzero"
|
||
d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" fill="#444"></path>
|
||
</svg>
|
||
<input type="text" name="q" aria-label="快速搜索"/>
|
||
<input type="submit" value="转向"/>
|
||
</form>
|
||
</nav>
|
||
<div class="menu-wrapper">
|
||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||
<div class="language_switcher_placeholder"></div>
|
||
<h3><a href="../contents.html">目录</a></h3>
|
||
<ul>
|
||
<li><a class="reference internal" href="#">3. 数据模型</a><ul>
|
||
<li><a class="reference internal" href="#objects-values-and-types">3.1. 对象、值与类型</a></li>
|
||
<li><a class="reference internal" href="#the-standard-type-hierarchy">3.2. 标准类型层级结构</a></li>
|
||
<li><a class="reference internal" href="#special-method-names">3.3. 特殊方法名称</a><ul>
|
||
<li><a class="reference internal" href="#basic-customization">3.3.1. 基本定制</a></li>
|
||
<li><a class="reference internal" href="#customizing-attribute-access">3.3.2. 自定义属性访问</a><ul>
|
||
<li><a class="reference internal" href="#customizing-module-attribute-access">3.3.2.1. 自定义模块属性访问</a></li>
|
||
<li><a class="reference internal" href="#implementing-descriptors">3.3.2.2. 实现描述器</a></li>
|
||
<li><a class="reference internal" href="#invoking-descriptors">3.3.2.3. 调用描述器</a></li>
|
||
<li><a class="reference internal" href="#slots">3.3.2.4. __slots__</a><ul>
|
||
<li><a class="reference internal" href="#notes-on-using-slots">3.3.2.4.1. 使用 <em>__slots__</em> 的注意事项</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#customizing-class-creation">3.3.3. 自定义类创建</a><ul>
|
||
<li><a class="reference internal" href="#metaclasses">3.3.3.1. 元类</a></li>
|
||
<li><a class="reference internal" href="#resolving-mro-entries">3.3.3.2. 解析 MRO 条目</a></li>
|
||
<li><a class="reference internal" href="#determining-the-appropriate-metaclass">3.3.3.3. 确定适当的元类</a></li>
|
||
<li><a class="reference internal" href="#preparing-the-class-namespace">3.3.3.4. 准备类命名空间</a></li>
|
||
<li><a class="reference internal" href="#executing-the-class-body">3.3.3.5. 执行类主体</a></li>
|
||
<li><a class="reference internal" href="#creating-the-class-object">3.3.3.6. 创建类对象</a></li>
|
||
<li><a class="reference internal" href="#uses-for-metaclasses">3.3.3.7. 元类的作用</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#customizing-instance-and-subclass-checks">3.3.4. 自定义实例及子类检查</a></li>
|
||
<li><a class="reference internal" href="#emulating-generic-types">3.3.5. 模拟泛型类型</a></li>
|
||
<li><a class="reference internal" href="#emulating-callable-objects">3.3.6. 模拟可调用对象</a></li>
|
||
<li><a class="reference internal" href="#emulating-container-types">3.3.7. 模拟容器类型</a></li>
|
||
<li><a class="reference internal" href="#emulating-numeric-types">3.3.8. 模拟数字类型</a></li>
|
||
<li><a class="reference internal" href="#with-statement-context-managers">3.3.9. with 语句上下文管理器</a></li>
|
||
<li><a class="reference internal" href="#special-method-lookup">3.3.10. 特殊方法查找</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#coroutines">3.4. 协程</a><ul>
|
||
<li><a class="reference internal" href="#awaitable-objects">3.4.1. 可等待对象</a></li>
|
||
<li><a class="reference internal" href="#coroutine-objects">3.4.2. 协程对象</a></li>
|
||
<li><a class="reference internal" href="#asynchronous-iterators">3.4.3. 异步迭代器</a></li>
|
||
<li><a class="reference internal" href="#asynchronous-context-managers">3.4.4. 异步上下文管理器</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
|
||
<h4>上一个主题</h4>
|
||
<p class="topless"><a href="lexical_analysis.html"
|
||
title="上一章"><span class="section-number">2. </span>词法分析</a></p>
|
||
<h4>下一个主题</h4>
|
||
<p class="topless"><a href="executionmodel.html"
|
||
title="下一章"><span class="section-number">4. </span>执行模型</a></p>
|
||
<div role="note" aria-label="source link">
|
||
<h3>本页</h3>
|
||
<ul class="this-page-menu">
|
||
<li><a href="../bugs.html">报告 Bug</a></li>
|
||
<li>
|
||
<a href="https://github.com/python/cpython/blob/3.8/Doc/reference/datamodel.rst"
|
||
rel="nofollow">显示源代码
|
||
</a>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</nav>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="outdated-warning" style="padding: .5em; text-align: center; background-color: #FFBABA; color: #6A0E0E;">
|
||
这个文档所针对的是一个已不再受支持的 Python 旧版本。
|
||
你应当升级版本,并阅读
|
||
<a href="/3/reference/datamodel.html"> Python 当前稳定版本的文档</a>.
|
||
</div>
|
||
|
||
<div class="related" role="navigation" aria-label="related navigation">
|
||
<h3>导航</h3>
|
||
<ul>
|
||
<li class="right" style="margin-right: 10px">
|
||
<a href="../genindex.html" title="总目录"
|
||
accesskey="I">索引</a></li>
|
||
<li class="right" >
|
||
<a href="../py-modindex.html" title="Python 模块索引"
|
||
>模块</a> |</li>
|
||
<li class="right" >
|
||
<a href="executionmodel.html" title="4. 执行模型"
|
||
accesskey="N">下一页</a> |</li>
|
||
<li class="right" >
|
||
<a href="lexical_analysis.html" title="2. 词法分析"
|
||
accesskey="P">上一页</a> |</li>
|
||
|
||
<li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||
<li class="switchers">
|
||
<div class="language_switcher_placeholder"></div>
|
||
<div class="version_switcher_placeholder"></div>
|
||
</li>
|
||
<li>
|
||
|
||
</li>
|
||
<li id="cpython-language-and-version">
|
||
<a href="../index.html">3.8.20 Documentation</a> »
|
||
</li>
|
||
|
||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python语言参考</a> »</li>
|
||
<li class="right">
|
||
|
||
|
||
<div class="inline-search" role="search">
|
||
<form class="inline-search" action="../search.html" method="get">
|
||
<input placeholder="快速搜索" aria-label="快速搜索" type="text" name="q" />
|
||
<input type="submit" value="转向" />
|
||
<input type="hidden" name="check_keywords" value="yes" />
|
||
<input type="hidden" name="area" value="default" />
|
||
</form>
|
||
</div>
|
||
|
|
||
</li>
|
||
|
||
</ul>
|
||
</div>
|
||
|
||
<div class="document">
|
||
<div class="documentwrapper">
|
||
<div class="bodywrapper">
|
||
<div class="body" role="main">
|
||
|
||
<section id="data-model">
|
||
<span id="datamodel"></span><h1><span class="section-number">3. </span>数据模型<a class="headerlink" href="#data-model" title="永久链接至标题">¶</a></h1>
|
||
<section id="objects-values-and-types">
|
||
<span id="objects"></span><h2><span class="section-number">3.1. </span>对象、值与类型<a class="headerlink" href="#objects-values-and-types" title="永久链接至标题">¶</a></h2>
|
||
<p id="index-0"><em class="dfn">对象</em> 是 Python 中对数据的抽象。 Python 程序中的所有数据都是由对象或对象间关系来表示的。 (从某种意义上说,按照冯·诺依曼的“存储程序计算机”模型,代码本身也是由对象来表示的。)</p>
|
||
<span class="target" id="index-1"></span><p>每个对象都有各自的标识号、类型和值。一个对象被创建后,它的 <em>标识号</em> 就绝不会改变;你可以将其理解为该对象在内存中的地址。 '<a class="reference internal" href="expressions.html#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a>' 运算符可以比较两个对象的标识号是否相同;<a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a> 函数能返回一个代表其标识号的整数。</p>
|
||
<div class="impl-detail compound">
|
||
<p><strong>CPython implementation detail:</strong> 在 CPython 中,<code class="docutils literal notranslate"><span class="pre">id(x)</span></code> 就是存放 <code class="docutils literal notranslate"><span class="pre">x</span></code> 的内存的地址。</p>
|
||
</div>
|
||
<p>对象的类型决定该对象所支持的操作 (例如 "对象是否有长度属性?") 并且定义了该类型的对象可能的取值。<a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> 函数能返回一个对象的类型 (类型本身也是对象)。与编号一样,一个对象的 <em class="dfn">类型</em> 也是不可改变的。<a class="footnote-reference brackets" href="#id8" id="id1">1</a></p>
|
||
<p>有些对象的 <em>值</em> 可以改变。值可以改变的对象被称为 <em>可变对象</em>;值不可以改变的对象就被称为 <em>不可变对象</em>。(一个不可变容器对象如果包含对可变对象的引用,当后者的值改变时,前者的值也会改变;但是该容器仍属于不可变对象,因为它所包含的对象集是不会改变的。因此,不可变并不严格等同于值不能改变,实际含义要更微妙。) 一个对象的可变性是由其类型决定的;例如,数字、字符串和元组是不可变的,而字典和列表是可变的。</p>
|
||
<p id="index-2">对象绝不会被显式地销毁;然而,当无法访问时它们可能会被作为垃圾回收。允许具体的实现推迟垃圾回收或完全省略此机制 --- 如何实现垃圾回收是实现的质量问题,只要可访问的对象不会被回收即可。</p>
|
||
<div class="impl-detail compound">
|
||
<p><strong>CPython implementation detail:</strong> CPython 目前使用带有 (可选) 延迟检测循环链接垃圾的引用计数方案,会在对象不可访问时立即回收其中的大部分,但不保证回收包含循环引用的垃圾。请查看 <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> 模块的文档了解如何控制循环垃圾的收集相关信息。其他实现会有不同的行为方式,CPython 现有方式也可能改变。不要依赖不可访问对象的立即终结机制 (所以你应当总是显式地关闭文件)。</p>
|
||
</div>
|
||
<p>注意:使用实现的跟踪或调试功能可能令正常情况下会被回收的对象继续存活。还要注意通过 '<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>...<a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>' 语句捕捉异常也可能令对象保持存活。</p>
|
||
<p>有些对象包含对 "外部" 资源的引用,例如打开文件或窗口。当对象被作为垃圾回收时这些资源也应该会被释放,但由于垃圾回收并不确保发生,这些对象还提供了明确地释放外部资源的操作,通常为一个 <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> 方法。强烈推荐在程序中显式关闭此类对象。'<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>...<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>' 语句和 '<a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>' 语句提供了进行此种操作的更便捷方式。</p>
|
||
<p id="index-3">有些对象包含对其他对象的引用;它们被称为 <em>容器</em>。容器的例子有元组、列表和字典等。这些引用是容器对象值的组成部分。在多数情况下,当谈论一个容器的值时,我们是指所包含对象的值而不是其编号;但是,当我们谈论一个容器的可变性时,则仅指其直接包含的对象的编号。因此,如果一个不可变容器 (例如元组) 包含对一个可变对象的引用,则当该可变对象被改变时容器的值也会改变。</p>
|
||
<p>类型会影响对象行为的几乎所有方面。甚至对象标识号的重要性也在某种程度上受到影响:对于不可变类型,会得出新值的运算实际上可能返回类型和值相同的现有对象的引用,而对于可变类型来说这是不允许的。例如在 <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">1;</span> <span class="pre">b</span> <span class="pre">=</span> <span class="pre">1</span></code> 之后,<code class="docutils literal notranslate"><span class="pre">a</span></code> 和 <code class="docutils literal notranslate"><span class="pre">b</span></code> 可能会指向同一个值为一的对象,也可能不会,这取决于具体实现,但是在 <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">[];</span> <span class="pre">d</span> <span class="pre">=</span> <span class="pre">[]</span></code> 之后,<code class="docutils literal notranslate"><span class="pre">c</span></code> 和 <code class="docutils literal notranslate"><span class="pre">d</span></code> 保证会指向两个不同、单独的新建空列表。(请注意 <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">d</span> <span class="pre">=</span> <span class="pre">[]</span></code> 则是将同一个对象赋值给 <code class="docutils literal notranslate"><span class="pre">c</span></code> 和 <code class="docutils literal notranslate"><span class="pre">d</span></code>。)</p>
|
||
</section>
|
||
<section id="the-standard-type-hierarchy">
|
||
<span id="types"></span><h2><span class="section-number">3.2. </span>标准类型层级结构<a class="headerlink" href="#the-standard-type-hierarchy" title="永久链接至标题">¶</a></h2>
|
||
<p id="index-4">以下是 Python 内置类型的列表。扩展模块 (具体实现会以 C, Java 或其他语言编写) 可以定义更多的类型。未来版本的 Python 可能会加入更多的类型 (例如有理数、高效存储的整型数组等等),不过新增类型往往都是通过标准库来提供的。</p>
|
||
<p id="index-5">以下部分类型的描述中包含有 '特殊属性列表' 段落。这些属性提供对具体实现的访问而非通常使用。它们的定义在未来可能会改变。</p>
|
||
<dl>
|
||
<dt>None</dt><dd><p id="index-6">此类型只有一种取值。是一个具有此值的单独对象。此对象通过内置名称 <code class="docutils literal notranslate"><span class="pre">None</span></code> 访问。在许多情况下它被用来表示空值,例如未显式指明返回值的函数将返回 None。它的逻辑值为假。</p>
|
||
</dd>
|
||
<dt>NotImplemented</dt><dd><p id="index-7">此类型只有一种取值。是一个具有此值的单独对象。此对象通过内置名称 <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> 访问。数值方法和丰富比较方法如未实现指定运算符表示的运算则应返回此值。(解释器会根据指定运算符继续尝试反向运算或其他回退操作)。它的逻辑值为真。</p>
|
||
<p>详情参见 <a class="reference internal" href="../library/numbers.html#implementing-the-arithmetic-operations"><span class="std std-ref">实现算术运算</span></a>。</p>
|
||
</dd>
|
||
<dt>Ellipsis</dt><dd><p id="index-8">此类型只有一种取值。是一个具有此值的单独对象。此对象通过字面值 <code class="docutils literal notranslate"><span class="pre">...</span></code> 或内置名称 <code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code> 访问。它的逻辑值为真。</p>
|
||
</dd>
|
||
<dt><a class="reference internal" href="../library/numbers.html#numbers.Number" title="numbers.Number"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Number</span></code></a></dt><dd><p id="index-9">此类对象由数字字面值创建,并会被作为算术运算符和算术内置函数的返回结果。数字对象是不可变的;一旦创建其值就不再改变。Python 中的数字当然非常类似数学中的数字,但也受限于计算机中的数字表示方法。</p>
|
||
<p>数字类的字符串表示形式,由 <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> 和 <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> 算出,具有以下属性:</p>
|
||
<ul class="simple">
|
||
<li><p>它们是有效的数字字面值,当被传给它们的类构造器时,将会产生具有原数字值的对象。</p></li>
|
||
<li><p>表示形式会在可能的情况下采用 10 进制。</p></li>
|
||
<li><p>开头的零,除小数点前可能存在的单个零之外,将不会被显示。</p></li>
|
||
<li><p>末尾的零,除小数点后可能存在的单个零之外,将不会被显示。</p></li>
|
||
<li><p>正负号仅在当数字为负值时会被显示。</p></li>
|
||
</ul>
|
||
<p>Python 区分整型数、浮点型数和复数:</p>
|
||
<dl>
|
||
<dt><a class="reference internal" href="../library/numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Integral</span></code></a></dt><dd><p id="index-10">此类对象表示数学中整数集合的成员 (包括正数和负数)。</p>
|
||
<p>整型数可细分为两种类型:</p>
|
||
<dl>
|
||
<dt>整型 (<a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>)</dt><dd><p>此类对象表示任意大小的数字,仅受限于可用的内存 (包括虚拟内存)。在变换和掩码运算中会以二进制表示,负数会以 2 的补码表示,看起来像是符号位向左延伸补满空位。</p>
|
||
</dd>
|
||
<dt>布尔型 (<a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a>)</dt><dd><p id="index-11">此类对象表示逻辑值 False 和 True。代表 <code class="docutils literal notranslate"><span class="pre">False</span></code> 和 <code class="docutils literal notranslate"><span class="pre">True</span></code> 值的两个对象是唯二的布尔对象。布尔类型是整型的子类型,两个布尔值在各种场合的行为分别类似于数值 0 和 1,例外情况只有在转换为字符串时分别返回字符串 <code class="docutils literal notranslate"><span class="pre">"False"</span></code> 或 <code class="docutils literal notranslate"><span class="pre">"True"</span></code>。</p>
|
||
</dd>
|
||
</dl>
|
||
<p id="index-12">整型数表示规则的目的是在涉及负整型数的变换和掩码运算时提供最为合理的解释。</p>
|
||
</dd>
|
||
<dt><a class="reference internal" href="../library/numbers.html#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Real</span></code></a> (<a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>)</dt><dd><p id="index-13">此类对象表示机器级的双精度浮点数。其所接受的取值范围和溢出处理将受制于底层的机器架构 (以及 C 或 Java 实现)。Python 不支持单精度浮点数;支持后者通常的理由是节省处理器和内存消耗,但这点节省相对于在 Python 中使用对象的开销来说太过微不足道,因此没有理由包含两种浮点数而令该语言变得复杂。</p>
|
||
</dd>
|
||
<dt><a class="reference internal" href="../library/numbers.html#numbers.Complex" title="numbers.Complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Complex</span></code></a> (<a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a>)</dt><dd><p id="index-14">此类对象以一对机器级的双精度浮点数来表示复数值。有关浮点数的附带规则对其同样有效。一个复数值 <code class="docutils literal notranslate"><span class="pre">z</span></code> 的实部和虚部可通过只读属性 <code class="docutils literal notranslate"><span class="pre">z.real</span></code> 和 <code class="docutils literal notranslate"><span class="pre">z.imag</span></code> 来获取。</p>
|
||
</dd>
|
||
</dl>
|
||
</dd>
|
||
<dt>序列</dt><dd><p id="index-15">此类对象表示以非负整数作为索引的有限有序集。内置函数 <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> 可返回一个序列的条目数量。当一个序列的长度为 <em>n</em> 时,索引集包含数字 0, 1, ..., <em>n</em>-1。序列 <em>a</em> 的条目 <em>i</em> 可通过 <code class="docutils literal notranslate"><span class="pre">a[i]</span></code> 选择。</p>
|
||
<p id="index-16">序列还支持切片: <code class="docutils literal notranslate"><span class="pre">a[i:j]</span></code> 选择索引号为 <em>k</em> 的所有条目,<em>i</em> <code class="docutils literal notranslate"><span class="pre"><=</span></code> <em>k</em> <code class="docutils literal notranslate"><span class="pre"><</span></code> <em>j</em>。当用作表达式时,序列的切片就是一个与序列类型相同的新序列。新序列的索引还是从 0 开始。</p>
|
||
<p>有些序列还支持带有第三个 "step" 形参的 "扩展切片": <code class="docutils literal notranslate"><span class="pre">a[i:j:k]</span></code> 选择 <em>a</em> 中索引号为 <em>x</em> 的所有条目,<code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">+</span> <span class="pre">n*k</span></code>, <em>n</em> <code class="docutils literal notranslate"><span class="pre">>=</span></code> <code class="docutils literal notranslate"><span class="pre">0</span></code> 且 <em>i</em> <code class="docutils literal notranslate"><span class="pre"><=</span></code> <em>x</em> <code class="docutils literal notranslate"><span class="pre"><</span></code> <em>j</em>。</p>
|
||
<p>序列可根据其可变性来加以区分:</p>
|
||
<dl>
|
||
<dt>不可变序列</dt><dd><p id="index-17">不可变序列类型的对象一旦创建就不能再改变。(如果对象包含对其他对象的引用,其中的可变对象就是可以改变的;但是,一个不可变对象所直接引用的对象集是不能改变的。)</p>
|
||
<p>以下类型属于不可变对象:</p>
|
||
<dl id="index-18">
|
||
<dt>字符串</dt><dd><p id="index-19">字符串是由 Unicode 码位值组成的序列。范围在 <code class="docutils literal notranslate"><span class="pre">U+0000</span> <span class="pre">-</span> <span class="pre">U+10FFFF</span></code> 之内的所有码位值都可在字符串中使用。Python 没有 <code class="xref c c-type docutils literal notranslate"><span class="pre">char</span></code> 类型;而是将字符串中的每个码位表示为一个长度为 <code class="docutils literal notranslate"><span class="pre">1</span></code> 的字符串对象。内置函数 <a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a> 可将一个码位由字符串形式转换成一个范围在 <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">-</span> <span class="pre">10FFFF</span></code> 之内的整型数;<a class="reference internal" href="../library/functions.html#chr" title="chr"><code class="xref py py-func docutils literal notranslate"><span class="pre">chr()</span></code></a> 可将一个范围在 <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">-</span> <span class="pre">10FFFF</span></code> 之内的整型数转换为长度为 <code class="docutils literal notranslate"><span class="pre">1</span></code> 的对应字符串对象。<a class="reference internal" href="../library/stdtypes.html#str.encode" title="str.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.encode()</span></code></a> 可以使用指定的文本编码将 <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> 转换为 <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>,而 <a class="reference internal" href="../library/stdtypes.html#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytes.decode()</span></code></a> 则可以实现反向的解码。</p>
|
||
</dd>
|
||
<dt>元组</dt><dd><p id="index-20">一个元组中的条目可以是任意 Python 对象。包含两个或以上条目的元组由逗号分隔的表达式构成。只有一个条目的元组 ('单项元组') 可通过在表达式后加一个逗号来构成 (一个表达式本身不能创建为元组,因为圆括号要用来设置表达式分组)。一个空元组可通过一对内容为空的圆括号创建。</p>
|
||
</dd>
|
||
<dt>字节串</dt><dd><p id="index-21">字节串对象是不可变的数组。其中每个条目都是一个 8 位字节,以取值范围 0 <= x < 256 的整型数表示。字节串字面值 (例如 <code class="docutils literal notranslate"><span class="pre">b'abc'</span></code>) 和内置的 <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytes()</span></code></a> 构造器可被用来创建字节串对象。字节串对象还可以通过 <a class="reference internal" href="../library/stdtypes.html#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> 方法解码为字符串。</p>
|
||
</dd>
|
||
</dl>
|
||
</dd>
|
||
<dt>可变序列</dt><dd><p id="index-22">可变序列在被创建后仍可被改变。下标和切片标注可被用作赋值和 <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> (删除) 语句的目标。</p>
|
||
<p>目前有两种内生可变序列类型:</p>
|
||
<dl>
|
||
<dt>列表</dt><dd><p id="index-23">列表中的条目可以是任意 Python 对象。列表由用方括号括起并由逗号分隔的多个表达式构成。(注意创建长度为 0 或 1 的列表无需使用特殊规则。)</p>
|
||
</dd>
|
||
<dt>字节数组</dt><dd><p id="index-24">字节数组对象属于可变数组。可以通过内置的 <a class="reference internal" href="../library/stdtypes.html#bytearray" title="bytearray"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytearray()</span></code></a> 构造器来创建。除了是可变的 (因而也是不可哈希的),在其他方面字节数组提供的接口和功能都与不可变的 <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象一致。</p>
|
||
</dd>
|
||
</dl>
|
||
<p id="index-25">扩展模块 <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> 提供了一个额外的可变序列类型示例,<a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> 模块也是如此。</p>
|
||
</dd>
|
||
</dl>
|
||
</dd>
|
||
<dt>集合类型</dt><dd><p id="index-26">此类对象表示由不重复且不可变对象组成的无序且有限的集合。因此它们不能通过下标来索引。但是它们可被迭代,也可用内置函数 <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> 返回集合中的条目数。集合常见的用处是快速成员检测,去除序列中的重复项,以及进行交、并、差和对称差等数学运算。</p>
|
||
<p>对于集合元素所采用的不可变规则与字典的键相同。注意数字类型遵循正常的数字比较规则: 如果两个数字相等 (例如 <code class="docutils literal notranslate"><span class="pre">1</span></code> 和 <code class="docutils literal notranslate"><span class="pre">1.0</span></code>),则同一集合中只能包含其中一个。</p>
|
||
<p>目前有两种内生集合类型:</p>
|
||
<dl>
|
||
<dt>集合</dt><dd><p id="index-27">此类对象表示可变集合。它们可通过内置的 <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-func docutils literal notranslate"><span class="pre">set()</span></code></a> 构造器创建,并且创建之后可以通过方法进行修改,例如 <code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code>。</p>
|
||
</dd>
|
||
<dt>冻结集合</dt><dd><p id="index-28">此类对象表示不可变集合。它们可通过内置的 <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-func docutils literal notranslate"><span class="pre">frozenset()</span></code></a> 构造器创建。由于 frozenset 对象不可变且 <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>,它可以被用作另一个集合的元素或是字典的键。</p>
|
||
</dd>
|
||
</dl>
|
||
</dd>
|
||
<dt>映射</dt><dd><p id="index-29">此类对象表示由任意索引集合所索引的对象的集合。通过下标 <code class="docutils literal notranslate"><span class="pre">a[k]</span></code> 可在映射 <code class="docutils literal notranslate"><span class="pre">a</span></code> 中选择索引为 <code class="docutils literal notranslate"><span class="pre">k</span></code> 的条目;这可以在表达式中使用,也可作为赋值或 <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> 语句的目标。内置函数 <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> 可返回一个映射中的条目数。</p>
|
||
<p>目前只有一种内生映射类型:</p>
|
||
<dl>
|
||
<dt>字典</dt><dd><p id="index-30">此类对象表示由几乎任意值作为索引的有限个对象的集合。不可作为键的值类型只有包含列表或字典或其他可变类型,通过值而非对象编号进行比较的值,其原因在于高效的字典实现需要使用键的哈希值以保持一致性。用作键的数字类型遵循正常的数字比较规则: 如果两个数字相等 (例如 <code class="docutils literal notranslate"><span class="pre">1</span></code> 和 <code class="docutils literal notranslate"><span class="pre">1.0</span></code>) 则它们均可来用来索引同一个字典条目。</p>
|
||
<p>字典会保留插入顺序,这意味着键将以它们被添加的顺序在字典中依次产生。 替换某个现有的键不会改变其顺序,但是移除某个键再重新插入则会将其添加到末尾而不会保留其原有位置。</p>
|
||
<p>字典是可变的;它们可通过 <code class="docutils literal notranslate"><span class="pre">{...}</span></code> 标注来创建 (参见 <a class="reference internal" href="expressions.html#dict"><span class="std std-ref">字典显示</span></a> 小节)。</p>
|
||
<p id="index-31">扩展模块 <a class="reference internal" href="../library/dbm.html#module-dbm.ndbm" title="dbm.ndbm: The standard "database" interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm.ndbm</span></code></a> 和 <a class="reference internal" href="../library/dbm.html#module-dbm.gnu" title="dbm.gnu: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm.gnu</span></code></a> 提供了额外的映射类型示例,<a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> 模块也是如此。</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">在 3.7 版更改: </span>在 Python 3.6 版之前字典不会保留插入顺序。 在 CPython 3.6 中插入顺序会被保留,但这在当时被当作是一个实现细节而非确定的语言特性。</p>
|
||
</div>
|
||
</dd>
|
||
</dl>
|
||
</dd>
|
||
<dt>可调用类型</dt><dd><p id="index-32">此类型可以被应用于函数调用操作 (参见 <a class="reference internal" href="expressions.html#calls"><span class="std std-ref">调用</span></a> 小节):</p>
|
||
<dl>
|
||
<dt>用户定义函数</dt><dd><p id="index-33">用户定义函数对象可通过函数定义来创建 (参见 <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">函数定义</span></a> 小节)。它被调用时应附带一个参数列表,其中包含的条目应与函数所定义的形参列表一致。</p>
|
||
<p>特殊属性:</p>
|
||
<table class="docutils align-default" id="index-34">
|
||
<colgroup>
|
||
<col style="width: 37%" />
|
||
<col style="width: 46%" />
|
||
<col style="width: 16%" />
|
||
</colgroup>
|
||
<thead>
|
||
<tr class="row-odd"><th class="head"><p>属性</p></th>
|
||
<th class="head"><p>含意</p></th>
|
||
<th class="head"></th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr class="row-even"><td><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code></p></td>
|
||
<td><p>该函数的文档字符串,没有则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>;不会被子类继承。</p></td>
|
||
<td><p>可写</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a></p></td>
|
||
<td><p>该函数的名称。</p></td>
|
||
<td><p>可写</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><a class="reference internal" href="../library/stdtypes.html#definition.__qualname__" title="definition.__qualname__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__qualname__</span></code></a></p></td>
|
||
<td><p>该函数的 <a class="reference internal" href="../glossary.html#term-qualified-name"><span class="xref std std-term">qualified name</span></a>。</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">3.3 新版功能.</span></p>
|
||
</div>
|
||
</td>
|
||
<td><p>可写</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code></p></td>
|
||
<td><p>该函数所属模块的名称,没有则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p></td>
|
||
<td><p>可写</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__defaults__</span></code></p></td>
|
||
<td><p>由具有默认值的参数的默认参数值组成的元组,如无任何参数具有默认值则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p></td>
|
||
<td><p>可写</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__code__</span></code></p></td>
|
||
<td><p>表示编译后的函数体的代码对象。</p></td>
|
||
<td><p>可写</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__globals__</span></code></p></td>
|
||
<td><p>对存放该函数中全局变量的字典的引用 --- 函数所属模块的全局命名空间。</p></td>
|
||
<td><p>只读</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a></p></td>
|
||
<td><p>命名空间支持的函数属性。</p></td>
|
||
<td><p>可写</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__closure__</span></code></p></td>
|
||
<td><p><code class="docutils literal notranslate"><span class="pre">None</span></code> 或包含该函数可用变量的绑定的单元的元组。有关 <code class="docutils literal notranslate"><span class="pre">cell_contents</span></code> 属性的详情见下。</p></td>
|
||
<td><p>只读</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code></p></td>
|
||
<td><p>包含参数标注的字典。字典的键是参数名,如存在返回标注则为 <code class="docutils literal notranslate"><span class="pre">'return'</span></code>。</p></td>
|
||
<td><p>可写</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__kwdefaults__</span></code></p></td>
|
||
<td><p>仅包含关键字参数默认值的字典。</p></td>
|
||
<td><p>可写</p></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<p>大部分标有 "Writable" 的属性均会检查赋值的类型。</p>
|
||
<p>函数对象也支持获取和设置任意属性,例如这可以被用来给函数附加元数据。使用正规的属性点号标注获取和设置此类属性。<em>注意当前实现仅支持用户定义函数属性。未来可能会增加支持内置函数属性。</em></p>
|
||
<p>单元对象具有 <code class="docutils literal notranslate"><span class="pre">cell_contents</span></code> 属性。这可被用来获取以及设置单元的值。</p>
|
||
<p>有关函数定义的额外信息可以从其代码对象中提取;参见下文对内部类型的描述。 <a class="reference internal" href="../library/types.html#types.CellType" title="types.CellType"><code class="xref py py-data docutils literal notranslate"><span class="pre">cell</span></code></a> 类型可以在 <a class="reference internal" href="../library/types.html#module-types" title="types: Names for built-in types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">types</span></code></a> 模块中访问。</p>
|
||
</dd>
|
||
<dt>实例方法</dt><dd><p id="index-35">实例方法用于结合类、类实例和任何可调用对象 (通常为用户定义函数)。</p>
|
||
<p id="index-36">特殊的只读属性: <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> 为类实例对象本身,<code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code> 为函数对象;<code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> 为方法的文档 (与 <code class="docutils literal notranslate"><span class="pre">__func__.__doc__</span></code> 作用相同);<a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> 为方法名称 (与 <code class="docutils literal notranslate"><span class="pre">__func__.__name__</span></code> 作用相同);<code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> 为方法所属模块的名称,没有则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
|
||
<p>方法还支持获取 (但不能设置) 下层函数对象的任意函数属性。</p>
|
||
<p>用户定义方法对象可在获取一个类的属性时被创建 (也可能通过该类的一个实例),如果该属性为用户定义函数对象或类方法对象。</p>
|
||
<p>当通过从类实例获取一个用户定义函数对象的方式创建一个实例方法对象时,类实例对象的 <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> 属性即为该实例,并会绑定方法对象。该新建方法的 <code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code> 属性就是原来的函数对象。</p>
|
||
<p>当通过从类或实例获取一个类方法对象的方式创建一个实例对象时,实例对象的 <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> 属性为该类本身,其 <code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code> 属性为类方法对应的下层函数对象。</p>
|
||
<p>当一个实例方法对象被调用时,会调用对应的下层函数 (<code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code>),并将类实例 (<code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code>) 插入参数列表的开头。例如,当 <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> 是一个包含了 <code class="xref py py-meth docutils literal notranslate"><span class="pre">f()</span></code> 函数定义的类,而 <code class="docutils literal notranslate"><span class="pre">x</span></code> 是 <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> 的一个实例,则调用 <code class="docutils literal notranslate"><span class="pre">x.f(1)</span></code> 就等同于调用 <code class="docutils literal notranslate"><span class="pre">C.f(x,</span> <span class="pre">1)</span></code>。</p>
|
||
<p>当一个实例方法对象是衍生自一个类方法对象时,保存在 <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> 中的 "类实例" 实际上会是该类本身,因此无论是调用 <code class="docutils literal notranslate"><span class="pre">x.f(1)</span></code> 还是 <code class="docutils literal notranslate"><span class="pre">C.f(1)</span></code> 都等同于调用 <code class="docutils literal notranslate"><span class="pre">f(C,1)</span></code>,其中 <code class="docutils literal notranslate"><span class="pre">f</span></code> 为对应的下层函数。</p>
|
||
<p>请注意从函数对象到实例方法对象的变换会在每一次从实例获取属性时发生。在某些情况下,一种高效的优化方式是将属性赋值给一个本地变量并调用该本地变量。还要注意这样的变换只发生于用户定义函数;其他可调用对象 (以及所有不可调用对象) 在被获取时都不会发生变换。还有一个需要关注的要点是作为一个类实例属性的用户定义函数不会被转换为绑定方法;这样的变换 <em>仅当</em> 函数是类属性时才会发生。</p>
|
||
</dd>
|
||
<dt>生成器函数</dt><dd><p id="index-37">一个使用 <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> 语句 (见 <a class="reference internal" href="simple_stmts.html#yield"><span class="std std-ref">yield 语句</span></a> 章节)的函数或方法被称作一个 <em class="dfn">生成器函数</em>。 这样的函数在被调用时,总是返回一个可以执行函数体的迭代器对象:调用该迭代器的 <a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iterator.__next__()</span></code></a> 方法将会导致这个函数一直运行直到它使用 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> 语句提供了一个值为止。 当这个函数执行 <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> 语句或者执行到末尾时,将引发 <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> 异常并且这个迭代器将到达所返回的值集合的末尾。</p>
|
||
</dd>
|
||
<dt>协程函数</dt><dd><p id="index-38">使用 <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> 来定义的函数或方法就被称为 <em class="dfn">协程函数</em>。这样的函数在被调用时会返回一个 <a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">coroutine</span></a> 对象。它可能包含 <a class="reference internal" href="expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> 表达式以及 <a class="reference internal" href="compound_stmts.html#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a> 和 <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> 语句。详情可参见 <a class="reference internal" href="#coroutine-objects"><span class="std std-ref">协程对象</span></a> 一节。</p>
|
||
</dd>
|
||
<dt>异步生成器函数</dt><dd><p id="index-39">使用 <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> 来定义并包含 <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> 语句的函数或方法就被称为 <em class="dfn">异步生成器函数</em>。这样的函数在被调用时会返回一个异步迭代器对象,该对象可在 <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> 语句中用来执行函数体。</p>
|
||
<p>调用异步迭代器的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">aiterator.__anext__()</span></code> 方法将会返回一个 <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a>,此对象会在被等待时执行直到使用 <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> 表达式输出一个值。当函数执行时到空的 <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> 语句或是最后一条语句时,将会引发 <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> 异常,异步迭代器也会到达要输出的值集合的末尾。</p>
|
||
</dd>
|
||
<dt>内置函数</dt><dd><p id="index-40">内置函数对象是对于 C 函数的外部封装。内置函数的例子包括 <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> 和 <a class="reference internal" href="../library/math.html#math.sin" title="math.sin"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.sin()</span></code></a> (<a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> 是一个标准内置模块)。内置函数参数的数量和类型由 C 函数决定。特殊的只读属性: <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> 是函数的文档字符串,如果没有则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>; <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> 是函数的名称; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> 设定为 <code class="docutils literal notranslate"><span class="pre">None</span></code> (参见下一条目); <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> 是函数所属模块的名称,如果没有则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
|
||
</dd>
|
||
<dt>内置方法</dt><dd><p id="index-41">此类型实际上是内置函数的另一种形式,只不过还包含了一个传入 C 函数的对象作为隐式的额外参数。内置方法的一个例子是 <code class="docutils literal notranslate"><span class="pre">alist.append()</span></code>,其中 <em>alist</em> 为一个列表对象。在此示例中,特殊的只读属性 <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> 会被设为 <em>alist</em> 所标记的对象。</p>
|
||
</dd>
|
||
<dt>类</dt><dd><p>类是可调用的。此种对象通常是作为“工厂”来创建自身的实例,类也可以有重载 <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> 的变体类型。调用的参数会传给 <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a>,而且通常也会传给 <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> 来初始化新的实例。</p>
|
||
</dd>
|
||
<dt>类实例</dt><dd><p>任意类的实例通过在所属类中定义 <a class="reference internal" href="#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> 方法即能成为可调用的对象。</p>
|
||
</dd>
|
||
</dl>
|
||
</dd>
|
||
<dt>模块</dt><dd><p id="index-42">模块是 Python 代码的基本组织单元,由 <a class="reference internal" href="import.html#importsystem"><span class="std std-ref">导入系统</span></a> 创建,由 <a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> 语句发起调用,或者通过 <a class="reference internal" href="../library/importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.import_module()</span></code></a> 和内置的 <a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a> 等函数发起调用。 模块对象具有由字典对象实现的命名空间(这是被模块中定义的函数的 <code class="docutils literal notranslate"><span class="pre">__globals__</span></code> 属性引用的字典)。 属性引用被转换为该字典中的查找,例如 <code class="docutils literal notranslate"><span class="pre">m.x</span></code> 相当于 <code class="docutils literal notranslate"><span class="pre">m.__dict__["x"]</span></code>。 模块对象不包含用于初始化模块的代码对象(因为初始化完成后不需要它)。</p>
|
||
<p>属性赋值会更新模块的命名空间字典,例如 <code class="docutils literal notranslate"><span class="pre">m.x</span> <span class="pre">=</span> <span class="pre">1</span></code> 等同于 <code class="docutils literal notranslate"><span class="pre">m.__dict__["x"]</span> <span class="pre">=</span> <span class="pre">1</span></code>。</p>
|
||
<p id="index-43">预定义的 (可写) 属性: <a class="reference internal" href="import.html#__name__" title="__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> 为模块的名称; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> 为模块的文档字符串,如果没有则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code> (可选) 为一个包含 <a class="reference internal" href="../glossary.html#term-variable-annotation"><span class="xref std std-term">变量标注</span></a> 的字典,它是在模块体执行时获取的; <a class="reference internal" href="import.html#__file__" title="__file__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code></a> 是模块对应的被加载文件的路径名,如果它是加载自一个文件的话。某些类型的模块可能没有 <a class="reference internal" href="import.html#__file__" title="__file__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code></a> 属性,例如 C 模块是静态链接到解释器内部的; 对于从一个共享库动态加载的扩展模块来说该属性为该共享库文件的路径名。</p>
|
||
<p id="index-44">特殊的只读属性: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> 为以字典对象表示的模块命名空间。</p>
|
||
<div class="impl-detail compound">
|
||
<p><strong>CPython implementation detail:</strong> 由于 CPython 清理模块字典的设定,当模块离开作用域时模块字典将会被清理,即使该字典还有活动的引用。想避免此问题,可复制该字典或保持模块状态以直接使用其字典。</p>
|
||
</div>
|
||
</dd>
|
||
<dt>自定义类</dt><dd><p>自定义类这种类型一般通过类定义来创建 (参见 <a class="reference internal" href="compound_stmts.html#class"><span class="std std-ref">类定义</span></a> 一节)。每个类都有通过一个字典对象实现的独立命名空间。类属性引用会被转化为在此字典中查找,例如 <code class="docutils literal notranslate"><span class="pre">C.x</span></code> 会被转化为 <code class="docutils literal notranslate"><span class="pre">C.__dict__["x"]</span></code> (不过也存在一些钩子对象以允许其他定位属性的方式)。当未在其中发现某个属性名称时,会继续在基类中查找。这种基类查找使用 C3 方法解析顺序,即使存在 '钻石形' 继承结构即有多条继承路径连到一个共同祖先也能保持正确的行为。有关 Python 使用的 C3 MRO 的详情可查看配合 2.3 版发布的文档 <a class="reference external" href="https://www.python.org/download/releases/2.3/mro/">https://www.python.org/download/releases/2.3/mro/</a>.</p>
|
||
<p id="index-45">当一个类属性引用 (假设类名为 <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>) 会产生一个类方法对象时,它将转化为一个 <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> 属性为 <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> 的实例方法对象。当其会产生一个静态方法对象时,它将转化为该静态方法对象所封装的对象。从类的 <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> 所包含内容以外获取属性的其他方式请参看 <a class="reference internal" href="#descriptors"><span class="std std-ref">实现描述器</span></a> 一节。</p>
|
||
<p id="index-46">类属性赋值会更新类的字典,但不会更新基类的字典。</p>
|
||
<p id="index-47">类对象可被调用 (见上文) 以产生一个类实例 (见下文)。</p>
|
||
<p id="index-48">特殊属性: <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> 为类的名称; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> 为类所在模块的名称; <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> 为包含类命名空间的字典; <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a> 为包含基类的元组,按其在基类列表中的出现顺序排列; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> 为类的文档字符串,如果没有则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code> (可选) 为一个包含 <a class="reference internal" href="../glossary.html#term-variable-annotation"><span class="xref std std-term">变量标注</span></a> 的字典,它是在类体执行时获取的。</p>
|
||
</dd>
|
||
<dt>类实例</dt><dd><p id="index-49">类实例可通过调用类对象来创建 (见上文)。每个类实例都有通过一个字典对象实现的独立命名空间,属性引用会首先在此字典中查找。当未在其中发现某个属性,而实例对应的类中有该属性时,会继续在类属性中查找。如果找到的类属性为一个用户定义函数对象,它会被转化为实例方法对象,其 <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> 属性即该实例。静态方法和类方法对象也会被转化;参见上文 "Classes" 一节。要了解其他通过类实例来获取相应类属性的方式可参见 <a class="reference internal" href="#descriptors"><span class="std std-ref">实现描述器</span></a> 一节,这样得到的属性可能与实际存放于类的 <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> 中的对象不同。如果未找到类属性,而对象对应的类具有 <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> 方法,则会调用该方法来满足查找要求。</p>
|
||
<p id="index-50">属性赋值和删除会更新实例的字典,但不会更新对应类的字典。如果类具有 <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> 或 <a class="reference internal" href="#object.__delattr__" title="object.__delattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delattr__()</span></code></a> 方法,则将调用方法而不再直接更新实例的字典。</p>
|
||
<p id="index-51">如果类实例具有某些特殊名称的方法,就可以伪装为数字、序列或映射。参见 <a class="reference internal" href="#specialnames"><span class="std std-ref">特殊方法名称</span></a> 一节。</p>
|
||
<p id="index-52">特殊属性: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> 为属性字典; <a class="reference internal" href="../library/stdtypes.html#instance.__class__" title="instance.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> 为实例对应的类。</p>
|
||
</dd>
|
||
<dt>I/O 对象 (或称文件对象)</dt><dd><p id="index-53"><a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a> 表示一个打开的文件。有多种快捷方式可用来创建文件对象: <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> 内置函数,以及 <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a>, <a class="reference internal" href="../library/os.html#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fdopen()</span></code></a> 和 socket 对象的 <a class="reference internal" href="../library/socket.html#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code></a> 方法 (还可能使用某些扩展模块所提供的其他函数或方法)。</p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> 和 <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> 会初始化为对应于解释器标准输入、输出和错误流的文件对象;它们都会以文本模式打开,因此都遵循 <a class="reference internal" href="../library/io.html#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.TextIOBase</span></code></a> 抽象类所定义的接口。</p>
|
||
</dd>
|
||
<dt>内部类型</dt><dd><p id="index-54">某些由解释器内部使用的类型也被暴露给用户。它们的定义可能随未来解释器版本的更新而变化,为内容完整起见在此处一并介绍。</p>
|
||
<dl id="index-55">
|
||
<dt>代码对象</dt><dd><p>代码对象表示 <em>编译为字节的</em> 可执行 Python 代码,或称 <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a>。代码对象和函数对象的区别在于函数对象包含对函数全局对象 (函数所属的模块) 的显式引用,而代码对象不包含上下文;而且默认参数值会存放于函数对象而不是代码对象内 (因为它们表示在运行时算出的值)。与函数对象不同,代码对象不可变,也不包含对可变对象的引用 (不论是直接还是间接)。</p>
|
||
<p id="index-56">特殊的只读属性: <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_name</span></code> 给出了函数名; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_argcount</span></code> 为位置参数的总数量 (包括仅限位置参数和带有默认值的参数); <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_posonlyargcount</span></code> 为仅限位置参数的数量 (包括带有默认值的参数); <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_kwonlyargcount</span></code> 为仅限关键字参数的数量 (包括带有默认值的参数); <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_nlocals</span></code> 为函数使用的局部变量的数量 (包括参数); <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_varnames</span></code> 为一个包含局部变量名称的元组 (参数名排在最前面); <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_cellvars</span></code> 为一个包含被嵌套函数所引用的局部变量名称的元组; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_freevars</span></code> 为一个包含自由变量名称的元组; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_code</span></code> 为一个表示字节码指令序列的字符口中; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_consts</span></code> 为一个包含字节码所使用的字面值的元组; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_names</span></code> 为一个包含字节码所使用的名称的元组; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_filename</span></code> 为被编码代码所在的文件名; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_firstlineno</span></code> 为函数首行的行号; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_lnotab</span></code> 为一个字符串,其中编码了从字节码偏移量到行号的映射 (详情参见解释器的源代码); <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_stacksize</span></code> 为要求的栈大小; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code> 为一个整数,其中编码了解释器所用的多个旗标。</p>
|
||
<p id="index-57">以下是可用于 <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code> 的标志位定义:如果函数使用 <code class="docutils literal notranslate"><span class="pre">*arguments</span></code> 语法来接受任意数量的位置参数,则 <code class="docutils literal notranslate"><span class="pre">0x04</span></code> 位被设置;如果函数使用 <code class="docutils literal notranslate"><span class="pre">**keywords</span></code> 语法来接受任意数量的关键字参数,则 <code class="docutils literal notranslate"><span class="pre">0x08</span></code> 位被设置;如果函数是一个生成器,则 <code class="docutils literal notranslate"><span class="pre">0x20</span></code> 位被设置。</p>
|
||
<p>未来特性声明 (<code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></code>) 也使用 <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code> 中的标志位来指明代码对象的编译是否启用特定的特性: 如果函数编译时启用未来除法特性则设置 <code class="docutils literal notranslate"><span class="pre">0x2000</span></code> 位; 在更早的 Python 版本中则使用 <code class="docutils literal notranslate"><span class="pre">0x10</span></code> 和 <code class="docutils literal notranslate"><span class="pre">0x1000</span></code> 位。</p>
|
||
<p><code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code> 中的其他位被保留为内部使用。</p>
|
||
<p id="index-58">如果代码对象表示一个函数,<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_consts</span></code> 中的第一项将是函数的文档字符串,如果未定义则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
|
||
</dd>
|
||
</dl>
|
||
<dl id="frame-objects">
|
||
<dt>帧对象</dt><dd><p id="index-59">帧对象表示执行帧。它们可能出现在回溯对象中 (见下文),还会被传递给注册跟踪函数。</p>
|
||
<p id="index-60">特殊的只读属性: <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_back</span></code> 为前一堆栈帧 (指向调用者),如是最底层堆栈帧则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_code</span></code> 为此帧中所执行的代码对象; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_locals</span></code> 为用于查找本地变量的字典; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_globals</span></code> 则用于查找全局变量; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_builtins</span></code> 用于查找内置 (固有) 名称; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_lasti</span></code> 给出精确指令 (这是代码对象的字节码字符串的一个索引)。</p>
|
||
<p>访问 <code class="docutils literal notranslate"><span class="pre">f_code</span></code> 会引发一个 <a class="reference internal" href="../library/sys.html#auditing"><span class="std std-ref">审计事件</span></a> <code class="docutils literal notranslate"><span class="pre">object.__getattr__</span></code>,附带参数 <code class="docutils literal notranslate"><span class="pre">obj</span></code> 和 <code class="docutils literal notranslate"><span class="pre">"f_code"</span></code>。</p>
|
||
<p id="index-61">特殊的可写属性: <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_trace</span></code>,如果不为 <code class="docutils literal notranslate"><span class="pre">None</span></code>,则是在代码执行期间调用各类事件的函数 (由调试器使用)。通常每个新源码行会触发一个事件 - 这可以通过将 <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_trace_lines</span></code> 设为 <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> 来禁用。</p>
|
||
<p>具体的实现 <em>可能</em> 会通过将 <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_trace_opcodes</span></code> 设为 <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> 来允许按操作码请求事件。请注意如果跟踪函数引发的异常逃逸到被跟踪的函数中,这可能会导致未定义的解释器行为。</p>
|
||
<p><code class="xref py py-attr docutils literal notranslate"><span class="pre">f_lineno</span></code> 为帧的当前行号 --- 在这里写入从一个跟踪函数内部跳转的指定行 (仅用于最底层的帧)。调试器可以通过写入 f_lineno 实现一个 Jump 命令 (即设置下一语句)。</p>
|
||
<p>帧对象支持一个方法:</p>
|
||
<dl class="method">
|
||
<dt id="frame.clear">
|
||
<code class="sig-prename descclassname">frame.</code><code class="sig-name descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#frame.clear" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>此方法清除该帧持有的全部对本地变量的引用。而且如果该帧属于一个生成器,生成器会被完成。这有助于打破包含帧对象的循环引用 (例如当捕获一个异常并保存其回溯在之后使用)。</p>
|
||
<p>如果该帧当前正在执行,则会引发 <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a></p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">3.4 新版功能.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
</dd>
|
||
</dl>
|
||
<dl id="traceback-objects">
|
||
<dt>回溯对象</dt><dd><p id="index-62">回溯对象表示一个异常的栈跟踪记录。当异常发生时会隐式地创建一个回溯对象,也可能通过调用 <a class="reference internal" href="../library/types.html#types.TracebackType" title="types.TracebackType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.TracebackType</span></code></a> 显式地创建。</p>
|
||
<p>对于隐式地创建的回溯对象,当查找异常句柄使得执行栈展开时,会在每个展开层级的当前回溯之前插入一个回溯对象。当进入一个异常句柄时,栈跟踪将对程序启用。(参见 <a class="reference internal" href="compound_stmts.html#try"><span class="std std-ref">try 语句</span></a> 一节。) 它可作为 <code class="docutils literal notranslate"><span class="pre">sys.exc_info()</span></code> 所返回的元组的第三项,以及所捕获异常的 <code class="docutils literal notranslate"><span class="pre">__traceback__</span></code> 属性被获取。</p>
|
||
<p>当程序不包含可用的句柄时,栈跟踪会 (以良好的格式) 写入标准错误流;如果解释器处于交互模式,它也可作为 <code class="docutils literal notranslate"><span class="pre">sys.last_traceback</span></code> 对用户启用。</p>
|
||
<p>对于显式创建的回溯对象,则由回溯对象的创建者来决定应该如何链接 <code class="docutils literal notranslate"><span class="pre">tb_next</span></code> 属性来构成完整的栈跟踪。</p>
|
||
<p id="index-63">特殊的只读属性: <code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_frame</span></code> 指向当前层级的执行帧; <code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_lineno</span></code> 给出发生异常所在的行号; <code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_lasti</span></code> 标示具体指令。如果异常发生于没有匹配的 except 子句或有 finally 子句的 <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> 语句中,回溯对象中的行号和最后指令可能与相应帧对象中行号不同。</p>
|
||
<p>访问 <code class="docutils literal notranslate"><span class="pre">tb_frame</span></code> 会引发一个 <a class="reference internal" href="../library/sys.html#auditing"><span class="std std-ref">审计事件</span></a> <code class="docutils literal notranslate"><span class="pre">object.__getattr__</span></code>,附带参数 <code class="docutils literal notranslate"><span class="pre">obj</span></code> 和 <code class="docutils literal notranslate"><span class="pre">"tb_frame"</span></code>。</p>
|
||
<p id="index-64">特殊的可写属性: <code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_next</span></code> 为栈跟踪中的下一层级 (通往发生异常的帧),如果没有下一层级则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">在 3.7 版更改: </span>回溯对象现在可以使用 Python 代码显式地实例化,现有实例的 <code class="docutils literal notranslate"><span class="pre">tb_next</span></code> 属性可以被更新。</p>
|
||
</div>
|
||
</dd>
|
||
<dt>切片对象</dt><dd><p id="index-65">切片对象用来表示 <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 方法用到的切片。 该对象也可使用内置的 <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-func docutils literal notranslate"><span class="pre">slice()</span></code></a> 函数来创建。</p>
|
||
<p id="index-66">特殊的只读属性: <code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code> 为下界; <code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code> 为上界; <code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code> 为步长值; 各值如省略则为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。这些属性可具有任意类型。</p>
|
||
<p>切片对象支持一个方法:</p>
|
||
<dl class="method">
|
||
<dt id="slice.indices">
|
||
<code class="sig-prename descclassname">slice.</code><code class="sig-name descname">indices</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">length</em><span class="sig-paren">)</span><a class="headerlink" href="#slice.indices" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>此方法接受一个整型参数 <em>length</em> 并计算在切片对象被应用到 <em>length</em> 指定长度的条目序列时切片的相关信息应如何描述。 其返回值为三个整型数组成的元组;这些数分别为切片的 <em>start</em> 和 <em>stop</em> 索引号以及 <em>step</em> 步长值。索引号缺失或越界则按照与正规切片相一致的方式处理。</p>
|
||
</dd></dl>
|
||
|
||
</dd>
|
||
<dt>静态方法对象</dt><dd><p>静态方法对象提供了一种避免上文所述将函数对象转换为方法对象的方式。静态方法对象为对任意其他对象的封装,通常用来封装用户定义方法对象。当从类或类实例获取一个静态方法对象时,实际返回的对象是封装的对象,它不会被进一步转换。静态方法对象自身不是可调用的,但它们所封装的对象通常都是可调用的。静态方法对象可通过内置的 <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> 构造器来创建。</p>
|
||
</dd>
|
||
<dt>类方法对象</dt><dd><p>类方法对象和静态方法一样是对其他对象的封装,会改变从类或类实例获取该对象的方式。类方法对象在此类获取操作中的行为已在上文 "用户定义方法" 一节中描述。类方法对象可通过内置的 <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> 构造器来创建。</p>
|
||
</dd>
|
||
</dl>
|
||
</dd>
|
||
</dl>
|
||
</section>
|
||
<section id="special-method-names">
|
||
<span id="specialnames"></span><h2><span class="section-number">3.3. </span>特殊方法名称<a class="headerlink" href="#special-method-names" title="永久链接至标题">¶</a></h2>
|
||
<p id="index-67">一个类可以通过定义具有特殊名称的方法来实现由特殊语法所引发的特定操作 (例如算术运算或下标与切片)。这是 Python 实现 <em class="dfn">操作符重载</em> 的方式,允许每个类自行定义基于操作符的特定行为。例如,如果一个类定义了名为 <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 的方法,并且 <code class="docutils literal notranslate"><span class="pre">x</span></code> 为该类的一个实例,则 <code class="docutils literal notranslate"><span class="pre">x[i]</span></code> 基本就等同于 <code class="docutils literal notranslate"><span class="pre">type(x).__getitem__(x,</span> <span class="pre">i)</span></code>。除非有说明例外情况,在没有定义适当方法的情况下尝试执行一种操作将引发一个异常 (通常为 <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> 或 <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>)。</p>
|
||
<p>将一个特殊方法设为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 表示对应的操作不可用。例如,如果一个类将 <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> 设为 <code class="docutils literal notranslate"><span class="pre">None</span></code>,则该类就是不可迭代的,因此对其实例调用 <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> 将引发一个 <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> (而不会回退至 <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>). <a class="footnote-reference brackets" href="#id9" id="id2">2</a></p>
|
||
<p>在实现模拟任何内置类型的类时,很重要的一点是模拟的实现程度对于被模拟对象来说应当是有意义的。例如,提取单个元素的操作对于某些序列来说是适宜的,但提取切片可能就没有意义。(这种情况的一个实例是 W3C 的文档对象模型中的 <code class="xref py py-class docutils literal notranslate"><span class="pre">NodeList</span></code> 接口。)</p>
|
||
<section id="basic-customization">
|
||
<span id="customization"></span><h3><span class="section-number">3.3.1. </span>基本定制<a class="headerlink" href="#basic-customization" title="永久链接至标题">¶</a></h3>
|
||
<dl class="method">
|
||
<dt id="object.__new__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__new__</code><span class="sig-paren">(</span><em class="sig-param">cls</em><span class="optional">[</span>, <em class="sig-param">...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__new__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-68">调用以创建一个 <em>cls</em> 类的新实例。<a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> 是一个静态方法 (因为是特例所以你不需要显式地声明),它会将所请求实例所属的类作为第一个参数。其余的参数会被传递给对象构造器表达式 (对类的调用)。<a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> 的返回值应为新对象实例 (通常是 <em>cls</em> 的实例)。</p>
|
||
<p>典型的实现会附带适宜的参数使用 <code class="docutils literal notranslate"><span class="pre">super().__new__(cls[,</span> <span class="pre">...])</span></code>,通过超类的 <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> 方法来创建一个类的新实例,然后根据需要修改新创建的实例再将其返回。</p>
|
||
<p>如果 <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> 在构造对象期间被发起调用并且它返回了一个 <em>cls</em> 的实例,则新实例的 <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> 方法将以 <code class="docutils literal notranslate"><span class="pre">__init__(self[,</span> <span class="pre">...])</span></code> 的形式被发起调用,其中 <em>self</em> 为新实例而其余的参数与被传给对象构造器的参数相同。</p>
|
||
<p>如果 <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> 未返回一个 <em>cls</em> 的实例,则新实例的 <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> 方法就不会被执行。</p>
|
||
<p><a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> 的目的主要是允许不可变类型的子类 (例如 int, str 或 tuple) 定制实例创建过程。它也常会在自定义元类中被重载以便定制类创建过程。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__init__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__init__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="optional">[</span>, <em class="sig-param">...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__init__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-69">在实例 (通过 <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a>) 被创建之后,返回调用者之前调用。其参数与传递给类构造器表达式的参数相同。一个基类如果有 <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> 方法,则其所派生的类如果也有 <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> 方法,就必须显式地调用它以确保实例基类部分的正确初始化;例如: <code class="docutils literal notranslate"><span class="pre">super().__init__([args...])</span></code>.</p>
|
||
<p>因为对象是由 <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> 和 <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> 协作构造完成的 (由 <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> 创建,并由 <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> 定制),所以 <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> 返回的值只能是 <code class="docutils literal notranslate"><span class="pre">None</span></code>,否则会在运行时引发 <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__del__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__del__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__del__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-70">在实例将被销毁时调用。 这还被称为终结器或析构器(不适当)。 如果一个基类具有 <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> 方法,则其所派生的类如果也有 <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> 方法,就必须显式地调用它以确保实例基类部分的正确清除。</p>
|
||
<p><a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> 方法可以 (但不推荐!) 通过创建一个该实例的新引用来推迟其销毁。这被称为对象 <em>重生</em>。<a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> 是否会在重生的对象将被销毁时再次被调用是由具体实现决定的 ;当前的 <a class="reference internal" href="../glossary.html#term-cpython"><span class="xref std std-term">CPython</span></a> 实现只会调用一次。</p>
|
||
<p>当解释器退出时不会确保为仍然存在的对象调用 <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> 方法。</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">注解</p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">x</span></code> 并不直接调用 <code class="docutils literal notranslate"><span class="pre">x.__del__()</span></code> --- 前者会将 <code class="docutils literal notranslate"><span class="pre">x</span></code> 的引用计数减一,而后者仅会在 <code class="docutils literal notranslate"><span class="pre">x</span></code> 的引用计数变为零时被调用。</p>
|
||
</div>
|
||
<div class="impl-detail compound">
|
||
<p class="compound-first"><strong>CPython implementation detail:</strong> It is possible for a reference cycle to prevent the reference count
|
||
of an object from going to zero. In this case, the cycle will be
|
||
later detected and deleted by the <a class="reference internal" href="../glossary.html#term-garbage-collection"><span class="xref std std-term">cyclic garbage collector</span></a>. A common cause of reference cycles is when
|
||
an exception has been caught in a local variable. The frame's
|
||
locals then reference the exception, which references its own
|
||
traceback, which references the locals of all frames caught in the
|
||
traceback.</p>
|
||
<div class="compound-last admonition seealso">
|
||
<p class="admonition-title">参见</p>
|
||
<p><a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> 模块的文档。</p>
|
||
</div>
|
||
</div>
|
||
<div class="admonition warning">
|
||
<p class="admonition-title">警告</p>
|
||
<p>由于调用 <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> 方法时周边状况已不确定,在其执行期间发生的异常将被忽略,改为打印一个警告到 <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>。特别地:</p>
|
||
<ul class="simple">
|
||
<li><p><a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> 可在任意代码被执行时启用,包括来自任意线程的代码。如果 <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> 需要接受锁或启用其他阻塞资源,可能会发生死锁,例如该资源已被为执行 <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> 而中断的代码所获取。</p></li>
|
||
<li><p><a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> 可以在解释器关闭阶段被执行。因此,它需要访问的全局变量(包含其他模块)可能已被删除或设为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。Python 会保证先删除模块中名称以单个下划线打头的全局变量再删除其他全局变量;如果已不存在其他对此类全局变量的引用,这有助于确保导入的模块在 <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> 方法被调用时仍然可用。</p></li>
|
||
</ul>
|
||
</div>
|
||
<span class="target" id="index-71"></span></dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__repr__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__repr__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__repr__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>由 <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> 内置函数调用以输出一个对象的“官方”字符串表示。如果可能,这应类似一个有效的 Python 表达式,能被用来重建具有相同取值的对象(只要有适当的环境)。如果这不可能,则应返回形式如 <code class="docutils literal notranslate"><span class="pre"><...some</span> <span class="pre">useful</span> <span class="pre">description...></span></code> 的字符串。返回值必须是一个字符串对象。如果一个类定义了 <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> 但未定义 <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a>,则在需要该类的实例的“非正式”字符串表示时也会使用 <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a>。</p>
|
||
<p>此方法通常被用于调试,因此确保其表示的内容包含丰富信息且无歧义是很重要的。</p>
|
||
<span class="target" id="index-72"></span></dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__str__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__str__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__str__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>通过 <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str(object)</span></code></a> 以及内置函数 <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> 和 <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> 调用以生成一个对象的“非正式”或格式良好的字符串表示。返回值必须为一个 <a class="reference internal" href="../library/stdtypes.html#textseq"><span class="std std-ref">字符串</span></a> 对象。</p>
|
||
<p>此方法与 <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__repr__()</span></code></a> 的不同点在于 <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> 并不预期返回一个有效的 Python 表达式:可以使用更方便或更准确的描述信息。</p>
|
||
<p>内置类型 <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> 所定义的默认实现会调用 <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__repr__()</span></code></a>。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__bytes__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__bytes__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__bytes__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-73">通过 <a class="reference internal" href="../library/functions.html#func-bytes"><span class="std std-ref">bytes</span></a> 调用以生成一个对象的字节串表示。这应该返回一个 <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 对象。</p>
|
||
<span class="target" id="index-74"></span></dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__format__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__format__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">format_spec</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__format__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>通过 <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> 内置函数、扩展、<a class="reference internal" href="lexical_analysis.html#f-strings"><span class="std std-ref">格式化字符串字面值</span></a> 的求值以及 <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> 方法调用以生成一个对象的“格式化”字符串表示。 <em>format_spec</em> 参数为包含所需格式选项描述的字符串。 <em>format_spec</em> 参数的解读是由实现 <a class="reference internal" href="#object.__format__" title="object.__format__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code></a> 的类型决定的,不过大多数类或是将格式化委托给某个内置类型,或是使用相似的格式化选项语法。</p>
|
||
<p>请参看 <a class="reference internal" href="../library/string.html#formatspec"><span class="std std-ref">格式规格迷你语言</span></a> 了解标准格式化语法的描述。</p>
|
||
<p>返回值必须为一个字符串对象。</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">在 3.4 版更改: </span><code class="docutils literal notranslate"><span class="pre">object</span></code> 本身的 __format__ 方法如果被传入任何非空字符,将会引发一个 <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>。</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">在 3.7 版更改: </span><code class="docutils literal notranslate"><span class="pre">object.__format__(x,</span> <span class="pre">'')</span></code> 现在等同于 <code class="docutils literal notranslate"><span class="pre">str(x)</span></code> 而不再是 <code class="docutils literal notranslate"><span class="pre">format(str(self),</span> <span class="pre">'')</span></code>。</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<span class="target" id="richcmpfuncs"></span><dl class="method">
|
||
<dt id="object.__lt__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__lt__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__lt__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__le__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__le__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__le__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__eq__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__eq__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__eq__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__ne__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__ne__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ne__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__gt__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__gt__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__gt__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__ge__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__ge__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ge__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-75">以上这些被称为“富比较”方法。运算符号与方法名称的对应关系如下:<code class="docutils literal notranslate"><span class="pre">x<y</span></code> 调用 <code class="docutils literal notranslate"><span class="pre">x.__lt__(y)</span></code>、<code class="docutils literal notranslate"><span class="pre">x<=y</span></code> 调用 <code class="docutils literal notranslate"><span class="pre">x.__le__(y)</span></code>、<code class="docutils literal notranslate"><span class="pre">x==y</span></code> 调用 <code class="docutils literal notranslate"><span class="pre">x.__eq__(y)</span></code>、<code class="docutils literal notranslate"><span class="pre">x!=y</span></code> 调用 <code class="docutils literal notranslate"><span class="pre">x.__ne__(y)</span></code>、<code class="docutils literal notranslate"><span class="pre">x>y</span></code> 调用 <code class="docutils literal notranslate"><span class="pre">x.__gt__(y)</span></code>、<code class="docutils literal notranslate"><span class="pre">x>=y</span></code> 调用 <code class="docutils literal notranslate"><span class="pre">x.__ge__(y)</span></code>。</p>
|
||
<p>如果指定的参数对没有相应的实现,富比较方法可能会返回单例对象 <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>。按照惯例,成功的比较会返回 <code class="docutils literal notranslate"><span class="pre">False</span></code> 或 <code class="docutils literal notranslate"><span class="pre">True</span></code>。不过实际上这些方法可以返回任意值,因此如果比较运算符是要用于布尔值判断(例如作为 <code class="docutils literal notranslate"><span class="pre">if</span></code> 语句的条件),Python 会对返回值调用 <a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-func docutils literal notranslate"><span class="pre">bool()</span></code></a> 以确定结果为真还是假。</p>
|
||
<p>在默认情况下,<code class="docutils literal notranslate"><span class="pre">object</span></code> 通过使用 <code class="docutils literal notranslate"><span class="pre">is</span></code> 来实现 <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a>,并在比较结果为假值时返回 <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>: <code class="docutils literal notranslate"><span class="pre">True</span> <span class="pre">if</span> <span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span> <span class="pre">else</span> <span class="pre">NotImplemented</span></code>。 对于 <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ne__()</span></code></a>,默认会委托给 <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> 并对结果取反,除非结果为 <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>。 比较运算符之间没有其他隐含关系或默认实现;例如,<code class="docutils literal notranslate"><span class="pre">(x<y</span> <span class="pre">or</span> <span class="pre">x==y)</span></code> 为真并不意味着 <code class="docutils literal notranslate"><span class="pre">x<=y</span></code>。 要根据单根运算自动生成排序操作,请参看 <a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.total_ordering()</span></code></a>。</p>
|
||
<p>请查看 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 的相关段落,了解创建可支持自定义比较运算并可用作字典键的 <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> 对象时要注意的一些事项。</p>
|
||
<p>这些方法并没有对调参数版本(在左边参数不支持该操作但右边参数支持时使用);而是 <a class="reference internal" href="#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a> 和 <a class="reference internal" href="#object.__gt__" title="object.__gt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__gt__()</span></code></a> 互为对方的反射, <a class="reference internal" href="#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__le__()</span></code></a> 和 <a class="reference internal" href="#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ge__()</span></code></a> 互为对方的反射,而 <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> 和 <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ne__()</span></code></a> 则是它们自己的反射。如果两个操作数的类型不同,且右操作数类型是左操作数类型的直接或间接子类,则优先选择右操作数的反射方法,否则优先选择左操作数的方法。虚拟子类不会被考虑。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__hash__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__hash__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__hash__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-76">通过内置函数 <a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> 调用以对哈希集的成员进行操作,属于哈希集的类型包括 <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>、<a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> 以及 <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>。<a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 应该返回一个整数。对象比较结果相同所需的唯一特征属性是其具有相同的哈希值;建议的做法是把参与比较的对象全部组件的哈希值混在一起,即将它们打包为一个元组并对该元组做哈希运算。例如:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="fm">__hash__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||
<span class="k">return</span> <span class="nb">hash</span><span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">nick</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">color</span><span class="p">))</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">注解</p>
|
||
<p><a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> 会从一个对象自定义的 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 方法返回值中截断为 <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code> 的大小。通常对 64 位构建为 8 字节,对 32 位构建为 4 字节。如果一个对象的 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 必须在不同位大小的构建上进行互操作,请确保检查全部所支持构建的宽度。做到这一点的简单方法是使用 <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-c</span> <span class="pre">"import</span> <span class="pre">sys;</span> <span class="pre">print(sys.hash_info.width)"</span></code>。</p>
|
||
</div>
|
||
<p>如果一个类没有定义 <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> 方法,那么也不应该定义 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 操作;如果它定义了 <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> 但没有定义 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>,则其实例将不可被用作可哈希集的项。如果一个类定义了可变对象并实现了 <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> 方法,则不应该实现 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>,因为可哈希集的实现要求键的哈希集是不可变的(如果对象的哈希值发生改变,它将处于错误的哈希桶中)。</p>
|
||
<p>用户定义的类默认带有 <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> 和 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 方法;使用它们与任何对象(自己除外)比较必定不相等,并且 <code class="docutils literal notranslate"><span class="pre">x.__hash__()</span></code> 会返回一个恰当的值以确保 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code> 同时意味着 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span></code> 且 <code class="docutils literal notranslate"><span class="pre">hash(x)</span> <span class="pre">==</span> <span class="pre">hash(y)</span></code>。</p>
|
||
<p>一个类如果重载了 <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> 且没有定义 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 则会将其 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 隐式地设为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。当一个类的 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 方法为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 时,该类的实例将在一个程序尝试获取其哈希值时正确地引发 <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>,并会在检测 <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">collections.abc.Hashable)</span></code> 时被正确地识别为不可哈希对象。</p>
|
||
<p>如果一个重载了 <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> 的类需要保留来自父类的 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 实现,则必须通过设置 <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre"><ParentClass>.__hash__</span></code> 来显式地告知解释器。</p>
|
||
<p>如果一个没有重载 <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> 的类需要去掉哈希支持,则应该在类定义中包含 <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code>。一个自定义了 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 以显式地引发 <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> 的类会被 <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">collections.abc.Hashable)</span></code> 调用错误地识别为可哈希对象。</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">注解</p>
|
||
<p>在默认情况下,str 和 bytes 对象的 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 值会使用一个不可预知的随机值“加盐”。 虽然它们在一个单独 Python 进程中会保持不变,但它们的值在重复运行的 Python 间是不可预测的。</p>
|
||
<p>这种做法是为了防止以下形式的拒绝服务攻击:通过仔细选择输入来利用字典插入操作在最坏情况下的执行效率即 O(n^2) 复杂度。详情见 <a class="reference external" href="http://www.ocert.org/advisories/ocert-2011-003.html">http://www.ocert.org/advisories/ocert-2011-003.html</a></p>
|
||
<p>改变哈希值会影响集合的迭代次序。Python 也从不保证这个次序不会被改变(通常它在 32 位和 64 位构建上是不一致的)。</p>
|
||
<p>另见 <span class="target" id="index-117"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHASHSEED"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHASHSEED</span></code></a>.</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">在 3.3 版更改: </span>默认启用哈希随机化。</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__bool__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__bool__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__bool__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-78">调用此方法以实现真值检测以及内置的 <code class="docutils literal notranslate"><span class="pre">bool()</span></code> 操作;应该返回 <code class="docutils literal notranslate"><span class="pre">False</span></code> 或 <code class="docutils literal notranslate"><span class="pre">True</span></code>。如果未定义此方法,则会查找并调用 <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> 并在其返回非零值时视对象的逻辑值为真。如果一个类既未定义 <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> 也未定义 <a class="reference internal" href="#object.__bool__" title="object.__bool__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__bool__()</span></code></a> 则视其所有实例的逻辑值为真。</p>
|
||
</dd></dl>
|
||
|
||
</section>
|
||
<section id="customizing-attribute-access">
|
||
<span id="attribute-access"></span><h3><span class="section-number">3.3.2. </span>自定义属性访问<a class="headerlink" href="#customizing-attribute-access" title="永久链接至标题">¶</a></h3>
|
||
<p>可以定义下列方法来自定义对类实例属性访问(<code class="docutils literal notranslate"><span class="pre">x.name</span></code> 的使用、赋值或删除)的具体含义.</p>
|
||
<dl class="method">
|
||
<dt id="object.__getattr__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__getattr__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getattr__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>当默认属性访问因引发 <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> 而失败时被调用 (可能是调用 <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> 时由于 <em>name</em> 不是一个实例属性或 <code class="docutils literal notranslate"><span class="pre">self</span></code> 的类关系树中的属性而引发了 <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>;或者是对 <em>name</em> 特性属性调用 <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> 时引发了 <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>)。此方法应当返回(找到的)属性值或是引发一个 <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> 异常。</p>
|
||
<p>请注意如果属性是通过正常机制找到的,<a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> 就不会被调用。(这是在 <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> 和 <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> 之间故意设置的不对称性。)这既是出于效率理由也是因为不这样设置的话 <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> 将无法访问实例的其他属性。要注意至少对于实例变量来说,你不必在实例属性字典中插入任何值(而是通过插入到其他对象)就可以模拟对它的完全控制。请参阅下面的 <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> 方法了解真正获取对属性访问的完全控制权的办法。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__getattribute__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__getattribute__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getattribute__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>此方法会无条件地被调用以实现对类实例属性的访问。如果类还定义了 <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>,则后者不会被调用,除非 <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> 显式地调用它或是引发了 <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>。此方法应当返回(找到的)属性值或是引发一个 <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> 异常。为了避免此方法中的无限递归,其实现应该总是调用具有相同名称的基类方法来访问它所需要的任何属性,例如 <code class="docutils literal notranslate"><span class="pre">object.__getattribute__(self,</span> <span class="pre">name)</span></code>。</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">注解</p>
|
||
<p>此方法在作为通过特定语法或内置函数隐式地调用的结果的情况下查找特殊方法时仍可能会被跳过。参见 <a class="reference internal" href="#special-lookup"><span class="std std-ref">特殊方法查找</span></a>。</p>
|
||
</div>
|
||
<p class="audit-hook">引发一个 <a class="reference internal" href="../library/sys.html#auditing"><span class="std std-ref">审计事件</span></a> <code class="docutils literal notranslate"><span class="pre">object.__getattr__</span></code>,附带参数 <code class="docutils literal notranslate"><span class="pre">obj</span></code>, <code class="docutils literal notranslate"><span class="pre">name</span></code>。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__setattr__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__setattr__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">name</em>, <em class="sig-param">value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setattr__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>此方法在一个属性被尝试赋值时被调用。这个调用会取代正常机制(即将值保存到实例字典)。 <em>name</em> 为属性名称, <em>value</em> 为要赋给属性的值。</p>
|
||
<p>如果 <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> 想要赋值给一个实例属性,它应该调用同名的基类方法,例如 <code class="docutils literal notranslate"><span class="pre">object.__setattr__(self,</span> <span class="pre">name,</span> <span class="pre">value)</span></code>。</p>
|
||
<p class="audit-hook">引发一个 <a class="reference internal" href="../library/sys.html#auditing"><span class="std std-ref">审计事件</span></a> <code class="docutils literal notranslate"><span class="pre">object.__setattr__</span></code>,附带参数 <code class="docutils literal notranslate"><span class="pre">obj</span></code>, <code class="docutils literal notranslate"><span class="pre">name</span></code>, <code class="docutils literal notranslate"><span class="pre">value</span></code>。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__delattr__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__delattr__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delattr__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>类似于 <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> 但其作用为删除而非赋值。此方法应该仅在 <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">obj.name</span></code> 对于该对象有意义时才被实现。</p>
|
||
<p class="audit-hook">引发一个 <a class="reference internal" href="../library/sys.html#auditing"><span class="std std-ref">审计事件</span></a> <code class="docutils literal notranslate"><span class="pre">object.__delattr__</span></code>,附带参数 <code class="docutils literal notranslate"><span class="pre">obj</span></code>, <code class="docutils literal notranslate"><span class="pre">name</span></code>。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__dir__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__dir__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__dir__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>此方法会在对相应对象调用 <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> 时被调用。返回值必须为一个序列。 <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> 会把返回的序列转换为列表并对其排序。</p>
|
||
</dd></dl>
|
||
|
||
<section id="customizing-module-attribute-access">
|
||
<h4><span class="section-number">3.3.2.1. </span>自定义模块属性访问<a class="headerlink" href="#customizing-module-attribute-access" title="永久链接至标题">¶</a></h4>
|
||
<p id="index-79">特殊名称 <code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> 和 <code class="docutils literal notranslate"><span class="pre">__dir__</span></code> 还可被用来自定义对模块属性的访问。模块层级的 <code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> 函数应当接受一个参数,其名称为一个属性名,并返回计算结果值或引发一个 <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>。如果通过正常查找即 <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__getattribute__()</span></code></a> 未在模块对象中找到某个属性,则 <code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> 会在模块的 <code class="docutils literal notranslate"><span class="pre">__dict__</span></code> 中查找,未找到时会引发一个 <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>。如果找到,它会以属性名被调用并返回结果值。</p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">__dir__</span></code> 函数应当不接受任何参数,并且返回一个表示模块中可访问名称的字符串序列。 此函数如果存在,将会重载一个模块中的标准 <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> 查找。</p>
|
||
<p>想要更细致地自定义模块的行为(设置属性和特性属性等待),可以将模块对象的 <code class="docutils literal notranslate"><span class="pre">__class__</span></code> 属性设置为一个 <a class="reference internal" href="../library/types.html#types.ModuleType" title="types.ModuleType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.ModuleType</span></code></a> 的子类。例如:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
|
||
<span class="kn">from</span> <span class="nn">types</span> <span class="kn">import</span> <span class="n">ModuleType</span>
|
||
|
||
<span class="k">class</span> <span class="nc">VerboseModule</span><span class="p">(</span><span class="n">ModuleType</span><span class="p">):</span>
|
||
<span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||
<span class="k">return</span> <span class="sa">f</span><span class="s1">'Verbose </span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="vm">__name__</span><span class="si">}</span><span class="s1">'</span>
|
||
|
||
<span class="k">def</span> <span class="fm">__setattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">attr</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
|
||
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Setting </span><span class="si">{</span><span class="n">attr</span><span class="si">}</span><span class="s1">...'</span><span class="p">)</span>
|
||
<span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__setattr__</span><span class="p">(</span><span class="n">attr</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
|
||
|
||
<span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="vm">__name__</span><span class="p">]</span><span class="o">.</span><span class="vm">__class__</span> <span class="o">=</span> <span class="n">VerboseModule</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">注解</p>
|
||
<p>定义模块的 <code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> 和设置模块的 <code class="docutils literal notranslate"><span class="pre">__class__</span></code> 只会影响使用属性访问语法进行的查找 -- 直接访问模块全局变量(不论是通过模块内的代码还是通过对模块全局字典的引用)是不受影响的。</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">在 3.5 版更改: </span><code class="docutils literal notranslate"><span class="pre">__class__</span></code> 模块属性改为可写。</p>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">3.7 新版功能: </span><code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> 和 <code class="docutils literal notranslate"><span class="pre">__dir__</span></code> 模块属性。</p>
|
||
</div>
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">参见</p>
|
||
<dl class="simple">
|
||
<dt><span class="target" id="index-118"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0562"><strong>PEP 562</strong></a> - 模块 __getattr__ 和 __dir__</dt><dd><p>描述用于模块的 <code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> 和 <code class="docutils literal notranslate"><span class="pre">__dir__</span></code> 函数。</p>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</section>
|
||
<section id="implementing-descriptors">
|
||
<span id="descriptors"></span><h4><span class="section-number">3.3.2.2. </span>实现描述器<a class="headerlink" href="#implementing-descriptors" title="永久链接至标题">¶</a></h4>
|
||
<p>以下方法仅当一个包含该方法的类(称为 <em>描述器</em> 类)的实例出现于一个 <em>所有者</em> 类中的时候才会起作用(该描述器必须在所有者类或其某个上级类的字典中)。在以下示例中,“属性”指的是名称为所有者类 <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> 中的特征属性的键名的属性。</p>
|
||
<dl class="method">
|
||
<dt id="object.__get__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__get__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">instance</em>, <em class="sig-param">owner=None</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__get__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>调用此方法以获取所有者类的属性(类属性访问)或该类的实例的属性(实例属性访问)。 可选的 <em>owner</em> 参数是所有者类而 <em>instance</em> 是被用来访问属性的实例,如果通过 <em>owner</em> 来访问属性则返回 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
|
||
<p>此方法应当返回计算得到的属性值或是引发 <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> 异常。</p>
|
||
<p><span class="target" id="index-119"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0252"><strong>PEP 252</strong></a> 指明 <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> 为带有一至二个参数的可调用对象。 Python 自身内置的描述器支持此规格定义;但是,某些第三方工具可能要求必须带两个参数。 Python 自身的 <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> 实现总是会传入两个参数,无论它们是否被要求提供。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__set__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__set__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">instance</em>, <em class="sig-param">value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__set__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>调用此方法以设置 <em>instance</em> 指定的所有者类的实例的属性为新值 <em>value</em>。</p>
|
||
<p>请注意,添加 <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> 或 <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a> 会将描述器变成“数据描述器”。 更多细节请参阅 <a class="reference internal" href="#descriptor-invocation"><span class="std std-ref">调用描述器</span></a>。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__delete__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__delete__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">instance</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delete__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>调用此方法以删除 <em>instance</em> 指定的所有者类的实例的属性。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__set_name__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__set_name__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">owner</em>, <em class="sig-param">name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__set_name__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>在所有者类 <em>owner</em> 创建时被调用。描述器会被赋值给 <em>name</em>。</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">注解</p>
|
||
<p><a class="reference internal" href="#object.__set_name__" title="object.__set_name__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set_name__()</span></code></a> 只是作为 <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a> 构造器的一部分被隐式地调用,因此在某个类被初次创建之后又额外添加一个描述器时,那就需要显式地调用它并且附带适当的形参:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
|
||
<span class="k">pass</span>
|
||
<span class="n">descr</span> <span class="o">=</span> <span class="n">custom_descriptor</span><span class="p">()</span>
|
||
<span class="n">A</span><span class="o">.</span><span class="n">attr</span> <span class="o">=</span> <span class="n">descr</span>
|
||
<span class="n">descr</span><span class="o">.</span><span class="n">__set_name__</span><span class="p">(</span><span class="n">A</span><span class="p">,</span> <span class="s1">'attr'</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>详情参见 <a class="reference internal" href="#class-object-creation"><span class="std std-ref">创建类对象</span></a>。</p>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">3.6 新版功能.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<p>属性 <code class="xref py py-attr docutils literal notranslate"><span class="pre">__objclass__</span></code> 会被 <a class="reference internal" href="../library/inspect.html#module-inspect" title="inspect: Extract information and source code from live objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">inspect</span></code></a> 模块解读为指定此对象定义所在的类(正确设置此属性有助于动态类属性的运行时内省)。对于可调用对象来说,它可以指明预期或要求提供一个特定类型(或子类)的实例作为第一个位置参数(例如,CPython 会为实现于 C 中的未绑定方法设置此属性)。</p>
|
||
</section>
|
||
<section id="invoking-descriptors">
|
||
<span id="descriptor-invocation"></span><h4><span class="section-number">3.3.2.3. </span>调用描述器<a class="headerlink" href="#invoking-descriptors" title="永久链接至标题">¶</a></h4>
|
||
<p>总的说来,描述器就是具有“绑定行为”的对象属性,其属性访问已被描述器协议中的方法所重载,包括 <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> 和 <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a>。如果一个对象定义了以上方法中的任意一个,它就被称为描述器。</p>
|
||
<p>属性访问的默认行为是从一个对象的字典中获取、设置或删除属性。例如,<code class="docutils literal notranslate"><span class="pre">a.x</span></code> 的查找顺序会从 <code class="docutils literal notranslate"><span class="pre">a.__dict__['x']</span></code> 开始,然后是 <code class="docutils literal notranslate"><span class="pre">type(a).__dict__['x']</span></code>,接下来依次查找 <code class="docutils literal notranslate"><span class="pre">type(a)</span></code> 的上级基类,不包括元类。</p>
|
||
<p>但是,如果找到的值是定义了某个描述器方法的对象,则 Python 可能会重载默认行为并转而发起调用描述器方法。这具体发生在优先级链的哪个环节则要根据所定义的描述器方法及其被调用的方式来决定。</p>
|
||
<p>描述器发起调用的开始点是一个绑定 <code class="docutils literal notranslate"><span class="pre">a.x</span></code>。参数的组合方式依 <code class="docutils literal notranslate"><span class="pre">a</span></code> 而定:</p>
|
||
<dl class="simple">
|
||
<dt>直接调用</dt><dd><p>最简单但最不常见的调用方式是用户代码直接发起调用一个描述器方法: <code class="docutils literal notranslate"><span class="pre">x.__get__(a)</span></code>。</p>
|
||
</dd>
|
||
<dt>实例绑定</dt><dd><p>如果绑定到一个对象实例,<code class="docutils literal notranslate"><span class="pre">a.x</span></code> 会被转换为调用: <code class="docutils literal notranslate"><span class="pre">type(a).__dict__['x'].__get__(a,</span> <span class="pre">type(a))</span></code>。</p>
|
||
</dd>
|
||
<dt>类绑定</dt><dd><p>如果绑定到一个类,<code class="docutils literal notranslate"><span class="pre">A.x</span></code> 会被转换为调用: <code class="docutils literal notranslate"><span class="pre">A.__dict__['x'].__get__(None,</span> <span class="pre">A)</span></code>。</p>
|
||
</dd>
|
||
<dt>超绑定</dt><dd><p>如果 <code class="docutils literal notranslate"><span class="pre">a</span></code> 是 <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-class docutils literal notranslate"><span class="pre">super</span></code></a> 的一个实例,则绑定 <code class="docutils literal notranslate"><span class="pre">super(B,</span> <span class="pre">obj).m()</span></code> 会在 <code class="docutils literal notranslate"><span class="pre">obj.__class__.__mro__</span></code> 中搜索 <code class="docutils literal notranslate"><span class="pre">B</span></code> 的直接上级基类 <code class="docutils literal notranslate"><span class="pre">A</span></code> 然后通过以下调用发起调用描述器: <code class="docutils literal notranslate"><span class="pre">A.__dict__['m'].__get__(obj,</span> <span class="pre">obj.__class__)</span></code>。</p>
|
||
</dd>
|
||
</dl>
|
||
<p>对于实例绑定,描述符调用的优先级取决于定义了哪些描述符方法。 描述符可以定义 <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>、<a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> 和 <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a> 的任意组合。 如果它没有定义 <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>,那么访问属性将返回描述符对象本身,除非对象的实例字典中有一个值。 如果描述符定义了 <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> 和/或 <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a>,则它是数据描述符; 如果两者都没有定义,则它是一个非数据描述符。 通常,数据描述符同时定义 <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> 和 <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a>,而非数据描述符只有 <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> 方法。 定义了 <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> 和 <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> 的数据描述符总是覆盖实例字典中的重定义。 相反,非数据描述符可以被实例覆盖。</p>
|
||
<p>Python 方法 (包括 <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> 和 <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a>) 都是作为非数据描述器来实现的。 因此实例可以重定义并重载方法。 这允许单个实例获得与相同类的其他实例不一样的行为。</p>
|
||
<p><a class="reference internal" href="../library/functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a> 函数是作为数据描述器来实现的。因此实例不能重载特性属性的行为。</p>
|
||
</section>
|
||
<section id="slots">
|
||
<span id="id3"></span><h4><span class="section-number">3.3.2.4. </span>__slots__<a class="headerlink" href="#slots" title="永久链接至标题">¶</a></h4>
|
||
<p><em>__slots__</em> 允许我们显式地声明数据成员(例如特征属性)并禁止创建 <em>__dict__</em> 和 <em>__weakref__</em> (除非是在 <em>__slots__</em> 中显式地声明或是在父类中可用。)</p>
|
||
<p>相比使用 <em>__dict__</em> 此方式可以显著地节省空间。 属性查找速度也可得到显著的提升。</p>
|
||
<dl class="data">
|
||
<dt id="object.__slots__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__slots__</code><a class="headerlink" href="#object.__slots__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>这个类变量可赋值为字符串、可迭代对象或由实例使用的变量名构成的字符串序列。 <em>__slots__</em> 会为已声明的变量保留空间,并阻止自动为每个实例创建 <em>__dict__</em> 和 <em>__weakref__</em>。</p>
|
||
</dd></dl>
|
||
|
||
<section id="notes-on-using-slots">
|
||
<h5><span class="section-number">3.3.2.4.1. </span>使用 <em>__slots__</em> 的注意事项<a class="headerlink" href="#notes-on-using-slots" title="永久链接至标题">¶</a></h5>
|
||
<ul class="simple">
|
||
<li><p>当继承自一个未定义 <em>__slots__</em> 的类时,实例的 <em>__dict__</em> 和 <em>__weakref__</em> 属性将总是可访问。</p></li>
|
||
<li><p>没有 <em>__dict__</em> 变量,实例就不能给未在 <em>__slots__</em> 定义中列出的新变量赋值。尝试给一个未列出的变量名赋值将引发 <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>。新变量需要动态赋值,就要将 <code class="docutils literal notranslate"><span class="pre">'__dict__'</span></code> 加入到 <em>__slots__</em> 声明的字符串序列中。</p></li>
|
||
<li><p>如果未给每个实例设置 <em>__weakref__</em> 变量,定义了 <em>__slots__</em> 的类就不支持对其实例的弱引用。如果需要弱引用支持,就要将 <code class="docutils literal notranslate"><span class="pre">'__weakref__'</span></code> 加入到 <em>__slots__</em> 声明的字符串序列中。</p></li>
|
||
<li><p><em>__slots__</em> 是通过为每个变量名创建描述器 (<a class="reference internal" href="#descriptors"><span class="std std-ref">实现描述器</span></a>) 在类层级上实现的。因此,类属性不能被用来为通过 <em>__slots__</em> 定义的实例变量设置默认值;否则,类属性就会覆盖描述器赋值。</p></li>
|
||
<li><p><em>__slots__</em> 声明的作用不只限于定义它的类。在父类中声明的 <em>__slots__</em> 在其子类中同样可用。不过,子类将会获得 <em>__dict__</em> 和 <em>__weakref__</em> 除非它们也定义了 <em>__slots__</em> (其中应该仅包含对任何 <em>额外</em> 名称的声明位置)。</p></li>
|
||
<li><p>如果一个类定义的位置在某个基类中也有定义,则由基类位置定义的实例变量将不可访问(除非通过直接从基类获取其描述器的方式)。这会使得程序的含义变成未定义。未来可能会添加一个防止此情况的检查。</p></li>
|
||
<li><p>非空的 <em>__slots__</em> 不适用于派生自“可变长度”内置类型例如 <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>、<a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> 和 <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> 的派生类。</p></li>
|
||
<li><p>任何非字符串可迭代对象都可以被赋值给 <em>__slots__</em>。映射也可以被使用;不过,未来可能会分别赋给每个键具有特殊含义的值。</p></li>
|
||
<li><p><em>__class__</em> 赋值仅在两个类具有相同的 <em>__slots__</em> 时才会起作用。</p></li>
|
||
<li><p>带有多个父类声明位置的多重继承也是可用的,但仅允许一个父类具有由声明位置创建的属性(其他基类必须具有空的位置布局) —— 违反规则将引发 <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>。</p></li>
|
||
<li><p>如果为 <em>__slots__</em> 使用了一个迭代器,则会为迭代器的每个值创建描述器。 但是 <em>__slots__</em> 属性将为一个空迭代器。</p></li>
|
||
</ul>
|
||
</section>
|
||
</section>
|
||
</section>
|
||
<section id="customizing-class-creation">
|
||
<span id="class-customization"></span><h3><span class="section-number">3.3.3. </span>自定义类创建<a class="headerlink" href="#customizing-class-creation" title="永久链接至标题">¶</a></h3>
|
||
<p>当一个类继承其他类时,那个类的 <em>__init_subclass__</em> 会被调用。这样就可以编写能够改变子类行为的类。这与类装饰器有紧密的关联,但是类装饰器是影响它们所应用的特定类,而 <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code> 则只作用于定义了该方法的类所派生的子类。</p>
|
||
<dl class="method">
|
||
<dt id="object.__init_subclass__">
|
||
<em class="property">classmethod </em><code class="sig-prename descclassname">object.</code><code class="sig-name descname">__init_subclass__</code><span class="sig-paren">(</span><em class="sig-param">cls</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__init_subclass__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>当所在类派生子类时此方法就会被调用。<em>cls</em> 将指向新的子类。如果定义为一个普通实例方法,此方法将被隐式地转换为类方法。</p>
|
||
<p>传入一个新类的关键字参数会被传给父类的 <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code>。为了与其他使用 <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code> 的类兼容,应当根据需要去掉部分关键字参数再将其余的传给基类,例如:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Philosopher</span><span class="p">:</span>
|
||
<span class="k">def</span> <span class="nf">__init_subclass__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">/</span><span class="p">,</span> <span class="n">default_name</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
|
||
<span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">__init_subclass__</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
|
||
<span class="bp">cls</span><span class="o">.</span><span class="n">default_name</span> <span class="o">=</span> <span class="n">default_name</span>
|
||
|
||
<span class="k">class</span> <span class="nc">AustralianPhilosopher</span><span class="p">(</span><span class="n">Philosopher</span><span class="p">,</span> <span class="n">default_name</span><span class="o">=</span><span class="s2">"Bruce"</span><span class="p">):</span>
|
||
<span class="k">pass</span>
|
||
</pre></div>
|
||
</div>
|
||
<p><code class="docutils literal notranslate"><span class="pre">object.__init_subclass__</span></code> 的默认实现什么都不做,只在带任意参数调用时引发一个错误。</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">注解</p>
|
||
<p>元类提示 <code class="docutils literal notranslate"><span class="pre">metaclass</span></code> 将被其它类型机制消耗掉,并不会被传给 <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code> 的实现。实际的元类(而非显式的提示)可通过 <code class="docutils literal notranslate"><span class="pre">type(cls)</span></code> 访问。</p>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">3.6 新版功能.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<section id="metaclasses">
|
||
<span id="id4"></span><h4><span class="section-number">3.3.3.1. </span>元类<a class="headerlink" href="#metaclasses" title="永久链接至标题">¶</a></h4>
|
||
<p id="index-82">默认情况下,类是使用 <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> 来构建的。类体会在一个新的命名空间内执行,类名会被局部绑定到 <code class="docutils literal notranslate"><span class="pre">type(name,</span> <span class="pre">bases,</span> <span class="pre">namespace)</span></code> 的结果。</p>
|
||
<p>类创建过程可通过在定义行传入 <code class="docutils literal notranslate"><span class="pre">metaclass</span></code> 关键字参数,或是通过继承一个包含此参数的现有类来进行定制。在以下示例中,<code class="docutils literal notranslate"><span class="pre">MyClass</span></code> 和 <code class="docutils literal notranslate"><span class="pre">MySubclass</span></code> 都是 <code class="docutils literal notranslate"><span class="pre">Meta</span></code> 的实例:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
|
||
<span class="k">pass</span>
|
||
|
||
<span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">Meta</span><span class="p">):</span>
|
||
<span class="k">pass</span>
|
||
|
||
<span class="k">class</span> <span class="nc">MySubclass</span><span class="p">(</span><span class="n">MyClass</span><span class="p">):</span>
|
||
<span class="k">pass</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>在类定义内指定的任何其他关键字参数都会在下面所描述的所有元类操作中进行传递。</p>
|
||
<p>当一个类定义被执行时,将发生以下步骤:</p>
|
||
<ul class="simple">
|
||
<li><p>解析 MRO 条目;</p></li>
|
||
<li><p>确定适当的元类;</p></li>
|
||
<li><p>准备类命名空间;</p></li>
|
||
<li><p>执行类主体;</p></li>
|
||
<li><p>创建类对象。</p></li>
|
||
</ul>
|
||
</section>
|
||
<section id="resolving-mro-entries">
|
||
<h4><span class="section-number">3.3.3.2. </span>解析 MRO 条目<a class="headerlink" href="#resolving-mro-entries" title="永久链接至标题">¶</a></h4>
|
||
<p>如果在类定义中出现的基类不是 <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a> 的实例,则使用 <code class="docutils literal notranslate"><span class="pre">__mro_entries__</span></code> 方法对其进行搜索,当找到结果时,它会以原始基类元组做参数进行调用。此方法必须返回类的元组以替代此基类被使用。元组可以为空,在此情况下原始基类将被忽略。</p>
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">参见</p>
|
||
<p><span class="target" id="index-120"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0560"><strong>PEP 560</strong></a> - 对 typing 模块和泛型类型的核心支持</p>
|
||
</div>
|
||
</section>
|
||
<section id="determining-the-appropriate-metaclass">
|
||
<h4><span class="section-number">3.3.3.3. </span>确定适当的元类<a class="headerlink" href="#determining-the-appropriate-metaclass" title="永久链接至标题">¶</a></h4>
|
||
<p id="index-84">为一个类定义确定适当的元类是根据以下规则:</p>
|
||
<ul class="simple">
|
||
<li><p>如果没有基类且没有显式指定元类,则使用 <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a>;</p></li>
|
||
<li><p>如果给出一个显式元类而且 <em>不是</em> <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> 的实例,则其会被直接用作元类;</p></li>
|
||
<li><p>如果给出一个 <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> 的实例作为显式元类,或是定义了基类,则使用最近派生的元类。</p></li>
|
||
</ul>
|
||
<p>最近派生的元类会从显式指定的元类(如果有)以及所有指定的基类的元类(即 <code class="docutils literal notranslate"><span class="pre">type(cls)</span></code>)中选取。最近派生的元类应为 <em>所有</em> 这些候选元类的一个子类型。如果没有一个候选元类符合该条件,则类定义将失败并抛出 <code class="docutils literal notranslate"><span class="pre">TypeError</span></code>。</p>
|
||
</section>
|
||
<section id="preparing-the-class-namespace">
|
||
<span id="prepare"></span><h4><span class="section-number">3.3.3.4. </span>准备类命名空间<a class="headerlink" href="#preparing-the-class-namespace" title="永久链接至标题">¶</a></h4>
|
||
<p id="index-85">一旦确定了适当的元类,则将准备好类命名空间。 如果元类具有 <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> 属性,它会以 <code class="docutils literal notranslate"><span class="pre">namespace</span> <span class="pre">=</span> <span class="pre">metaclass.__prepare__(name,</span> <span class="pre">bases,</span> <span class="pre">**kwds)</span></code> 的形式被调用(其中如果有任何额外的关键字参数,则应当来自类定义)。 <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> 方法应该被实现为 <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a>。 <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> 所返回的命名空间会被传入 <code class="docutils literal notranslate"><span class="pre">__new__</span></code>,但是当最终的类对象被创建时,该命名空间会被拷贝到一个新的 <code class="docutils literal notranslate"><span class="pre">dict</span></code> 中。</p>
|
||
<p>如果元类没有 <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> 属性,则类命名空间将初始化为一个空的有序映射。</p>
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">参见</p>
|
||
<dl class="simple">
|
||
<dt><span class="target" id="index-121"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3115"><strong>PEP 3115</strong></a> - Python 3000 中的元类</dt><dd><p>引入 <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> 命名空间钩子</p>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</section>
|
||
<section id="executing-the-class-body">
|
||
<h4><span class="section-number">3.3.3.5. </span>执行类主体<a class="headerlink" href="#executing-the-class-body" title="永久链接至标题">¶</a></h4>
|
||
<p id="index-87">类主体会以(类似于) <code class="docutils literal notranslate"><span class="pre">exec(body,</span> <span class="pre">globals(),</span> <span class="pre">namespace)</span></code> 的形式被执行。普通调用与 <a class="reference internal" href="../library/functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a> 的关键区别在于当类定义发生于函数内部时,词法作用域允许类主体(包括任何方法)引用来自当前和外部作用域的名称。</p>
|
||
<p>但是,即使当类定义发生于函数内部时,在类内部定义的方法仍然无法看到在类作用域层次上定义的名称。类变量必须通过实例的第一个形参或类方法来访问,或者是通过下一节中描述的隐式词法作用域的 <code class="docutils literal notranslate"><span class="pre">__class__</span></code> 引用。</p>
|
||
</section>
|
||
<section id="creating-the-class-object">
|
||
<span id="class-object-creation"></span><h4><span class="section-number">3.3.3.6. </span>创建类对象<a class="headerlink" href="#creating-the-class-object" title="永久链接至标题">¶</a></h4>
|
||
<p id="index-88">一旦执行类主体完成填充类命名空间,将通过调用 <code class="docutils literal notranslate"><span class="pre">metaclass(name,</span> <span class="pre">bases,</span> <span class="pre">namespace,</span> <span class="pre">**kwds)</span></code> 创建类对象(此处的附加关键字参数与传入 <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> 的相同)。</p>
|
||
<p>如果类主体中有任何方法引用了 <code class="docutils literal notranslate"><span class="pre">__class__</span></code> 或 <code class="docutils literal notranslate"><span class="pre">super</span></code>,这个类对象会通过零参数形式的 <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>. <code class="docutils literal notranslate"><span class="pre">__class__</span></code> 所引用,这是由编译器所创建的隐式闭包引用。这使用零参数形式的 <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> 能够正确标识正在基于词法作用域来定义的类,而被用于进行当前调用的类或实例则是基于传递给方法的第一个参数来标识的。</p>
|
||
<div class="impl-detail compound">
|
||
<p><strong>CPython implementation detail:</strong> 在 CPython 3.6 及之后的版本中,<code class="docutils literal notranslate"><span class="pre">__class__</span></code> 单元会作为类命名空间中的 <code class="docutils literal notranslate"><span class="pre">__classcell__</span></code> 条目被传给元类。 如果存在,它必须被向上传播给 <code class="docutils literal notranslate"><span class="pre">type.__new__</span></code> 调用,以便能正确地初始化该类。 如果不这样做,在 Python 3.8 中将引发 <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>。</p>
|
||
</div>
|
||
<p>当使用默认的元类 <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a> 或者任何最终会调用 <code class="docutils literal notranslate"><span class="pre">type.__new__</span></code> 的元类时,以下额外的自定义步骤将在创建类对象之后被发起调用:</p>
|
||
<ul class="simple">
|
||
<li><p>首先,<code class="docutils literal notranslate"><span class="pre">type.__new__</span></code> 将收集类命名空间中所有定义了 <a class="reference internal" href="#object.__set_name__" title="object.__set_name__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set_name__()</span></code></a> 方法的描述器;</p></li>
|
||
<li><p>接下来,所有这些 <code class="docutils literal notranslate"><span class="pre">__set_name__</span></code> 方法将使用所定义的类和特定描述器所赋的名称进行调用;</p></li>
|
||
<li><p>最后,将在新类根据方法解析顺序所确定的直接父类上调用 <a class="reference internal" href="#object.__init_subclass__" title="object.__init_subclass__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init_subclass__()</span></code></a> 钩子。</p></li>
|
||
</ul>
|
||
<p>在类对象创建之后,它会被传给包含在类定义中的类装饰器(如果有的话),得到的对象将作为已定义的类绑定到局部命名空间。</p>
|
||
<p>当通过 <code class="docutils literal notranslate"><span class="pre">type.__new__</span></code> 创建一个新类时,提供以作为命名空间形参的对象会被复制到一个新的有序映射并丢弃原对象。这个新副本包装于一个只读代理中,后者则成为类对象的 <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> 属性。</p>
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">参见</p>
|
||
<dl class="simple">
|
||
<dt><span class="target" id="index-122"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3135"><strong>PEP 3135</strong></a> - 新的超类型</dt><dd><p>描述隐式的 <code class="docutils literal notranslate"><span class="pre">__class__</span></code> 闭包引用</p>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</section>
|
||
<section id="uses-for-metaclasses">
|
||
<h4><span class="section-number">3.3.3.7. </span>元类的作用<a class="headerlink" href="#uses-for-metaclasses" title="永久链接至标题">¶</a></h4>
|
||
<p>元类的潜在作用非常广泛。已经过尝试的设想包括枚举、日志、接口检查、自动委托、自动特征属性创建、代理、框架以及自动资源锁定/同步等等。</p>
|
||
</section>
|
||
</section>
|
||
<section id="customizing-instance-and-subclass-checks">
|
||
<h3><span class="section-number">3.3.4. </span>自定义实例及子类检查<a class="headerlink" href="#customizing-instance-and-subclass-checks" title="永久链接至标题">¶</a></h3>
|
||
<p>以下方法被用来重载 <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> 和 <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> 内置函数的默认行为。</p>
|
||
<p>特别地,元类 <a class="reference internal" href="../library/abc.html#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">abc.ABCMeta</span></code></a> 实现了这些方法以便允许将抽象基类(ABC)作为“虚拟基类”添加到任何类或类型(包括内置类型),包括其他 ABC 之中。</p>
|
||
<dl class="method">
|
||
<dt id="class.__instancecheck__">
|
||
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__instancecheck__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">instance</em><span class="sig-paren">)</span><a class="headerlink" href="#class.__instancecheck__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>如果 <em>instance</em> 应被视为 <em>class</em> 的一个(直接或间接)实例则返回真值。如果定义了此方法,则会被调用以实现 <code class="docutils literal notranslate"><span class="pre">isinstance(instance,</span> <span class="pre">class)</span></code>。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="class.__subclasscheck__">
|
||
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__subclasscheck__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">subclass</em><span class="sig-paren">)</span><a class="headerlink" href="#class.__subclasscheck__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>Return true 如果 <em>subclass</em> 应被视为 <em>class</em> 的一个(直接或间接)子类则返回真值。如果定义了此方法,则会被调用以实现 <code class="docutils literal notranslate"><span class="pre">issubclass(subclass,</span> <span class="pre">class)</span></code>。</p>
|
||
</dd></dl>
|
||
|
||
<p>请注意这些方法的查找是基于类的类型(元类)。它们不能作为类方法在实际的类中被定义。这与基于实例被调用的特殊方法的查找是一致的,只有在此情况下实例本身被当作是类。</p>
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">参见</p>
|
||
<dl class="simple">
|
||
<dt><span class="target" id="index-123"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a> - 引入抽象基类</dt><dd><p>新增功能描述,通过 <a class="reference internal" href="#class.__instancecheck__" title="class.__instancecheck__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__instancecheck__()</span></code></a> 和 <a class="reference internal" href="#class.__subclasscheck__" title="class.__subclasscheck__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__subclasscheck__()</span></code></a> 来定制 <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> 和 <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> 行为,加入此功能的动机是出于向该语言添加抽象基类的内容(参见 <a class="reference internal" href="../library/abc.html#module-abc" title="abc: Abstract base classes according to :pep:`3119`."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> 模块)。</p>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</section>
|
||
<section id="emulating-generic-types">
|
||
<h3><span class="section-number">3.3.5. </span>模拟泛型类型<a class="headerlink" href="#emulating-generic-types" title="永久链接至标题">¶</a></h3>
|
||
<p>通过定义一个特殊方法,可以实现由 <span class="target" id="index-124"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a> 所规定的泛型类语法 (例如 <code class="docutils literal notranslate"><span class="pre">List[int]</span></code>):</p>
|
||
<dl class="method">
|
||
<dt id="object.__class_getitem__">
|
||
<em class="property">classmethod </em><code class="sig-prename descclassname">object.</code><code class="sig-name descname">__class_getitem__</code><span class="sig-paren">(</span><em class="sig-param">cls</em>, <em class="sig-param">key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__class_getitem__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>按照 <em>key</em> 参数指定的类型返回一个表示泛型类的专门化对象。</p>
|
||
</dd></dl>
|
||
|
||
<p>此方法的查找会基于对象自身,并且当定义于类体内部时,此方法将隐式地成为类方法。请注意,此机制主要是被保留用于静态类型提示,不鼓励在其他场合使用。</p>
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">参见</p>
|
||
<p><span class="target" id="index-125"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0560"><strong>PEP 560</strong></a> - 对 typing 模块和泛型类型的核心支持</p>
|
||
</div>
|
||
</section>
|
||
<section id="emulating-callable-objects">
|
||
<span id="callable-types"></span><h3><span class="section-number">3.3.6. </span>模拟可调用对象<a class="headerlink" href="#emulating-callable-objects" title="永久链接至标题">¶</a></h3>
|
||
<dl class="method">
|
||
<dt id="object.__call__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__call__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="optional">[</span>, <em class="sig-param">args...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__call__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-93">此方法会在实例作为一个函数被“调用”时被调用;如果定义了此方法,则 <code class="docutils literal notranslate"><span class="pre">x(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code> 就大致可以被改写为 <code class="docutils literal notranslate"><span class="pre">type(x).__call__(x,</span> <span class="pre">arg1,</span> <span class="pre">...)</span></code>。</p>
|
||
</dd></dl>
|
||
|
||
</section>
|
||
<section id="emulating-container-types">
|
||
<span id="sequence-types"></span><h3><span class="section-number">3.3.7. </span>模拟容器类型<a class="headerlink" href="#emulating-container-types" title="永久链接至标题">¶</a></h3>
|
||
<p>可以定义下列方法来实现容器对象。 容器通常属于序列(如列表或元组)或映射(如字典),但也存在其他形式的容器。 前几个方法集被用于模拟序列或是模拟映射;两者的不同之处在于序列允许的键应为整数 <em>k</em> 且 <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre"><=</span> <span class="pre">k</span> <span class="pre"><</span> <span class="pre">N</span></code> 其中 <em>N</em> 是序列或定义指定区间的项的切片对象的长度。 此外还建议让映射提供 <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">setdefault()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code> 以及 <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> 等方法,它们的行为应与 Python 标准字典对象的相应方法类似。 此外 <a class="reference internal" href="../library/collections.abc.html#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections.abc</span></code></a> 模块提供了一个 <a class="reference internal" href="../library/collections.abc.html#collections.abc.MutableMapping" title="collections.abc.MutableMapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code></a> 抽象基类以便根据由 <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>, <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a>, 和 <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code> 组成的基本集来创建所需的方法。 可变序列还应像 Python 标准列表对象那样提供 <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">index()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">insert()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">reverse()</span></code> 和 <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> 等方法。 最后,序列类型还应通过定义下文描述的 <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a>, <a class="reference internal" href="#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__radd__()</span></code></a>, <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a>, <a class="reference internal" href="#object.__mul__" title="object.__mul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__mul__()</span></code></a>, <a class="reference internal" href="#object.__rmul__" title="object.__rmul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rmul__()</span></code></a> 和 <a class="reference internal" href="#object.__imul__" title="object.__imul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__imul__()</span></code></a> 等方法来实现加法(指拼接)和乘法(指重复);它们不应定义其他数值运算符。 此外还建议映射和序列都实现 <a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> 方法以允许高效地使用 <code class="docutils literal notranslate"><span class="pre">in</span></code> 运算符;对于映射,<code class="docutils literal notranslate"><span class="pre">in</span></code> 应该搜索映射的键;对于序列,则应搜索其中的值。 另外还建议映射和序列都实现 <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> 方法以允许高效地迭代容器中的条目;对于映射,<a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> 应当迭代对象的键;对于序列,则应当迭代其中的值。</p>
|
||
<dl class="method">
|
||
<dt id="object.__len__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__len__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__len__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-94">调用此方法以实现内置函数 <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a>。应该返回对象的长度,以一个 <code class="docutils literal notranslate"><span class="pre">>=</span></code> 0 的整数表示。此外,如果一个对象未定义 <a class="reference internal" href="#object.__bool__" title="object.__bool__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__bool__()</span></code></a> 方法而其 <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> 方法返回值为零,则在布尔运算中会被视为假值。</p>
|
||
<div class="impl-detail compound">
|
||
<p><strong>CPython implementation detail:</strong> 在 CPython 中,要求长度最大为 <a class="reference internal" href="../library/sys.html#sys.maxsize" title="sys.maxsize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.maxsize</span></code></a>。如果长度大于 <code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.maxsize</span></code> 则某些特性 (例如 <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a>) 可能会引发 <a class="reference internal" href="../library/exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>。要通过真值检测来防止引发 <code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code>,对象必须定义 <a class="reference internal" href="#object.__bool__" title="object.__bool__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__bool__()</span></code></a> 方法。</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__length_hint__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__length_hint__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__length_hint__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>调用此方法以实现 <a class="reference internal" href="../library/operator.html#operator.length_hint" title="operator.length_hint"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.length_hint()</span></code></a>。 应该返回对象长度的估计值(可能大于或小于实际长度)。 此长度应为一个 <code class="docutils literal notranslate"><span class="pre">>=</span></code> 0 的整数。 返回值也可以为 <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-const docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>,这会被视作与 <code class="docutils literal notranslate"><span class="pre">__length_hint__</span></code> 方法完全不存在时一样处理。 此方法纯粹是为了优化性能,并不要求正确无误。</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">3.4 新版功能.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<div class="admonition note" id="index-95">
|
||
<p class="admonition-title">注解</p>
|
||
<p>切片是通过下述三个专门方法完成的。以下形式的调用</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="n">b</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>会为转写为</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">a</span><span class="p">[</span><span class="nb">slice</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="kc">None</span><span class="p">)]</span> <span class="o">=</span> <span class="n">b</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>其他形式以此类推。略去的切片项总是以 <code class="docutils literal notranslate"><span class="pre">None</span></code> 补全。</p>
|
||
</div>
|
||
<dl class="method">
|
||
<dt id="object.__getitem__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__getitem__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getitem__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>调用此方法以实现 <code class="docutils literal notranslate"><span class="pre">self[key]</span></code> 的求值。对于序列类型,接受的键应为整数和切片对象。请注意负数索引(如果类想要模拟序列类型)的特殊解读是取决于 <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 方法。如果 <em>key</em> 的类型不正确则会引发 <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> 异常;如果为序列索引集范围以外的值(在进行任何负数索引的特殊解读之后)则应引发 <a class="reference internal" href="../library/exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> 异常。对于映射类型,如果 <em>key</em> 找不到(不在容器中)则应引发 <a class="reference internal" href="../library/exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> 异常。</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">注解</p>
|
||
<p><a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> 循环在有不合法索引时会期待捕获 <a class="reference internal" href="../library/exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> 以便正确地检测到序列的结束。</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__setitem__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__setitem__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">key</em>, <em class="sig-param">value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setitem__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>调用此方法以实现向 <code class="docutils literal notranslate"><span class="pre">self[key]</span></code> 赋值。注意事项与 <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 相同。为对象实现此方法应该仅限于需要映射允许基于键修改值或添加键,或是序列允许元素被替换时。不正确的 <em>key</em> 值所引发的异常应与 <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 方法的情况相同。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__delitem__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__delitem__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delitem__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>调用此方法以实现 <code class="docutils literal notranslate"><span class="pre">self[key]</span></code> 的删除。注意事项与 <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 相同。为对象实现此方法应该权限于需要映射允许移除键,或是序列允许移除元素时。不正确的 <em>key</em> 值所引发的异常应与 <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 方法的情况相同。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__missing__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__missing__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__missing__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>此方法由 <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 在找不到字典中的键时调用以实现 dict 子类的 <code class="docutils literal notranslate"><span class="pre">self[key]</span></code>。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__iter__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__iter__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iter__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>此方法在需要为容器创建迭代器时被调用。此方法应该返回一个新的迭代器对象,它能够逐个迭代容器中的所有对象。对于映射,它应该逐个迭代容器中的键。</p>
|
||
<p>迭代器对象也需要实现此方法;它们需要返回对象自身。有关迭代器对象的详情请参看 <a class="reference internal" href="../library/stdtypes.html#typeiter"><span class="std std-ref">迭代器类型</span></a> 一节。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__reversed__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__reversed__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__reversed__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>此方法(如果存在)会被 <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> 内置函数调用以实现逆向迭代。它应当返回一个新的以逆序逐个迭代容器内所有对象的迭代器对象。</p>
|
||
<p>如果未提供 <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a> 方法,则 <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> 内置函数将回退到使用序列协议 (<a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> 和 <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>)。支持序列协议的对象应当仅在能够提供比 <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> 所提供的实现更高效的实现时才提供 <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a> 方法。</p>
|
||
</dd></dl>
|
||
|
||
<p>成员检测运算符 (<a class="reference internal" href="expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> 和 <a class="reference internal" href="expressions.html#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a>) 通常以对容器进行逐个迭代的方式来实现。 不过,容器对象可以提供以下特殊方法并采用更有效率的实现,这样也不要求对象必须为可迭代对象。</p>
|
||
<dl class="method">
|
||
<dt id="object.__contains__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__contains__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">item</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__contains__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>调用此方法以实现成员检测运算符。如果 <em>item</em> 是 <em>self</em> 的成员则应返回真,否则返回假。对于映射类型,此检测应基于映射的键而不是值或者键值对。</p>
|
||
<p>对于未定义 <a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> 的对象,成员检测将首先尝试通过 <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> 进行迭代,然后再使用 <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 的旧式序列迭代协议,参看 <a class="reference internal" href="expressions.html#membership-test-details"><span class="std std-ref">语言参考中的相应部分</span></a>。</p>
|
||
</dd></dl>
|
||
|
||
</section>
|
||
<section id="emulating-numeric-types">
|
||
<span id="numeric-types"></span><h3><span class="section-number">3.3.8. </span>模拟数字类型<a class="headerlink" href="#emulating-numeric-types" title="永久链接至标题">¶</a></h3>
|
||
<p>定义以下方法即可模拟数字类型。特定种类的数字不支持的运算(例如非整数不能进行位运算)所对应的方法应当保持未定义状态。</p>
|
||
<dl class="method">
|
||
<dt id="object.__add__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__add__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__add__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__sub__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__sub__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__sub__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__mul__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__mul__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__mul__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__matmul__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__matmul__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__matmul__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__truediv__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__truediv__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__truediv__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__floordiv__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__floordiv__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__floordiv__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__mod__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__mod__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__mod__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__divmod__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__divmod__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__divmod__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__pow__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__pow__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="optional">[</span>, <em class="sig-param">modulo</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__pow__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__lshift__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__lshift__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__lshift__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rshift__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rshift__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rshift__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__and__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__and__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__and__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__xor__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__xor__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__xor__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__or__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__or__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__or__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-96">调用这些方法来实现二进制算术运算 (<code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">@</span></code>, <code class="docutils literal notranslate"><span class="pre">/</span></code>, <code class="docutils literal notranslate"><span class="pre">//</span></code>, <code class="docutils literal notranslate"><span class="pre">%</span></code>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">**</span></code>, <code class="docutils literal notranslate"><span class="pre"><<</span></code>, <code class="docutils literal notranslate"><span class="pre">>></span></code>, <code class="docutils literal notranslate"><span class="pre">&</span></code>, <code class="docutils literal notranslate"><span class="pre">^</span></code>, <code class="docutils literal notranslate"><span class="pre">|</span></code>)。例如,求表达式 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code> 的值,其中 <em>x</em> 是具有 <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a> 方法的类的一个实例,则会调用 <code class="docutils literal notranslate"><span class="pre">x.__add__(y)</span></code>。<a class="reference internal" href="#object.__divmod__" title="object.__divmod__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__divmod__()</span></code></a> 方法应该等价于使用 <a class="reference internal" href="#object.__floordiv__" title="object.__floordiv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__floordiv__()</span></code></a> 和 <a class="reference internal" href="#object.__mod__" title="object.__mod__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__mod__()</span></code></a>,它不应该被关联到 <a class="reference internal" href="#object.__truediv__" title="object.__truediv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__truediv__()</span></code></a>。请注意如果要支持三元版本的内置 <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> 函数,则 <a class="reference internal" href="#object.__pow__" title="object.__pow__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__pow__()</span></code></a> 的定义应该接受可选的第三个参数。</p>
|
||
<p>如果这些方法中的某一个不支持与所提供参数进行运算,它应该返回 <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__radd__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__radd__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__radd__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rsub__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rsub__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rsub__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rmul__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rmul__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmul__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rmatmul__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rmatmul__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmatmul__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rtruediv__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rtruediv__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rtruediv__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rfloordiv__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rfloordiv__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rfloordiv__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rmod__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rmod__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmod__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rdivmod__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rdivmod__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rdivmod__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rpow__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rpow__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="optional">[</span>, <em class="sig-param">modulo</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__rpow__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rlshift__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rlshift__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rlshift__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rrshift__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rrshift__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rrshift__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rand__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rand__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rand__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__rxor__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__rxor__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rxor__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__ror__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__ror__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ror__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-97">调用这些方法来实现具有反射(交换)操作数的二进制算术运算 (<code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">@</span></code>, <code class="docutils literal notranslate"><span class="pre">/</span></code>, <code class="docutils literal notranslate"><span class="pre">//</span></code>, <code class="docutils literal notranslate"><span class="pre">%</span></code>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">**</span></code>, <code class="docutils literal notranslate"><span class="pre"><<</span></code>, <code class="docutils literal notranslate"><span class="pre">>></span></code>, <code class="docutils literal notranslate"><span class="pre">&</span></code>, <code class="docutils literal notranslate"><span class="pre">^</span></code>, <code class="docutils literal notranslate"><span class="pre">|</span></code>)。这些成员函数仅会在左操作数不支持相应运算 <a class="footnote-reference brackets" href="#id10" id="id5">3</a> 且两个操作数类型不同时被调用。<a class="footnote-reference brackets" href="#id11" id="id6">4</a> 例如,求表达式 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></code> 的值,其中 <em>y</em> 是具有 <a class="reference internal" href="#object.__rsub__" title="object.__rsub__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rsub__()</span></code></a> 方法的类的一个实例,则当 <code class="docutils literal notranslate"><span class="pre">x.__sub__(y)</span></code> 返回 <em>NotImplemented</em> 时会调用 <code class="docutils literal notranslate"><span class="pre">y.__rsub__(x)</span></code>。</p>
|
||
<p id="index-98">请注意三元版的 <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> 并不会尝试调用 <a class="reference internal" href="#object.__rpow__" title="object.__rpow__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rpow__()</span></code></a> (因为强制转换规则会太过复杂)。</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">注解</p>
|
||
<p>如果右操作数类型为左操作数类型的一个子类,且该子类提供了指定运算的反射方法,则此方法将先于左操作数的非反射方法被调用。 此行为可允许子类重载其祖先类的运算符。</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__iadd__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__iadd__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iadd__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__isub__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__isub__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__isub__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__imul__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__imul__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imul__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__imatmul__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__imatmul__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imatmul__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__itruediv__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__itruediv__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__itruediv__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__ifloordiv__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__ifloordiv__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ifloordiv__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__imod__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__imod__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imod__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__ipow__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__ipow__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="optional">[</span>, <em class="sig-param">modulo</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__ipow__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__ilshift__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__ilshift__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ilshift__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__irshift__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__irshift__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__irshift__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__iand__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__iand__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iand__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__ixor__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__ixor__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ixor__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__ior__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__ior__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ior__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>调用这些方法来实现扩展算术赋值 (<code class="docutils literal notranslate"><span class="pre">+=</span></code>, <code class="docutils literal notranslate"><span class="pre">-=</span></code>, <code class="docutils literal notranslate"><span class="pre">*=</span></code>, <code class="docutils literal notranslate"><span class="pre">@=</span></code>, <code class="docutils literal notranslate"><span class="pre">/=</span></code>, <code class="docutils literal notranslate"><span class="pre">//=</span></code>, <code class="docutils literal notranslate"><span class="pre">%=</span></code>, <code class="docutils literal notranslate"><span class="pre">**=</span></code>, <code class="docutils literal notranslate"><span class="pre"><<=</span></code>, <code class="docutils literal notranslate"><span class="pre">>>=</span></code>, <code class="docutils literal notranslate"><span class="pre">&=</span></code>, <code class="docutils literal notranslate"><span class="pre">^=</span></code>, <code class="docutils literal notranslate"><span class="pre">|=</span></code>)。这些方法应该尝试进行自身操作 (修改 <em>self</em>) 并返回结果 (结果应该但并非必须为 <em>self</em>)。如果某个方法未被定义,相应的扩展算术赋值将回退到普通方法。例如,如果 <em>x</em> 是具有 <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a> 方法的类的一个实例,则 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+=</span> <span class="pre">y</span></code> 就等价于 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">x.__iadd__(y)</span></code>。否则就如 <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code> 的求值一样选择 <code class="docutils literal notranslate"><span class="pre">x.__add__(y)</span></code> 和 <code class="docutils literal notranslate"><span class="pre">y.__radd__(x)</span></code>。在某些情况下,扩展赋值可导致未预期的错误 (参见 <a class="reference internal" href="../faq/programming.html#faq-augmented-assignment-tuple-error"><span class="std std-ref">为什么 a_tuple[i] += ['item'] 会引发异常?</span></a>),但此行为实际上是数据模型的一个组成部分。</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">注解</p>
|
||
<p>由于 <code class="docutils literal notranslate"><span class="pre">**=</span></code> 的分配机制存在一个错误,定义了 <a class="reference internal" href="#object.__ipow__" title="object.__ipow__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ipow__()</span></code></a> 但是返回 <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> 的类将无法回退到 <code class="docutils literal notranslate"><span class="pre">x.__pow__(y)</span></code> 和 <code class="docutils literal notranslate"><span class="pre">y.__rpow__(x)</span></code>。 此错误在 Python 3.10 中被修正。</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__neg__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__neg__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__neg__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__pos__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__pos__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__pos__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__abs__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__abs__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__abs__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__invert__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__invert__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__invert__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-99">调用此方法以实现一元算术运算 (<code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">+</span></code>, <a class="reference internal" href="../library/functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a> 和 <code class="docutils literal notranslate"><span class="pre">~</span></code>)。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__complex__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__complex__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__complex__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__int__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__int__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__int__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__float__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__float__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__float__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-100">调用这些方法以实现内置函数 <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a>, <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> 和 <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>。应当返回一个相应类型的值。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__index__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__index__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__index__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>调用此方法以实现 <a class="reference internal" href="../library/operator.html#operator.index" title="operator.index"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.index()</span></code></a> 以及 Python 需要无损地将数字对象转换为整数对象的场合(例如切片或是内置的 <a class="reference internal" href="../library/functions.html#bin" title="bin"><code class="xref py py-func docutils literal notranslate"><span class="pre">bin()</span></code></a>, <a class="reference internal" href="../library/functions.html#hex" title="hex"><code class="xref py py-func docutils literal notranslate"><span class="pre">hex()</span></code></a> 和 <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a> 函数)。 存在此方法表明数字对象属于整数类型。 必须返回一个整数。</p>
|
||
<p>如果未定义 <a class="reference internal" href="#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a>, <a class="reference internal" href="#object.__float__" title="object.__float__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__float__()</span></code></a> 和 <a class="reference internal" href="#object.__complex__" title="object.__complex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__complex__()</span></code></a> 则相应的内置函数 <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>, <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> 和 <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a> 将回退为 <a class="reference internal" href="#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a>。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__round__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__round__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="optional">[</span>, <em class="sig-param">ndigits</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__round__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__trunc__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__trunc__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__trunc__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__floor__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__floor__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__floor__" title="永久链接至目标">¶</a></dt>
|
||
<dt id="object.__ceil__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__ceil__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ceil__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p id="index-101">调用这些方法以实现内置函数 <a class="reference internal" href="../library/functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a> 以及 <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> 函数 <a class="reference internal" href="../library/math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">trunc()</span></code></a>, <a class="reference internal" href="../library/math.html#math.floor" title="math.floor"><code class="xref py py-func docutils literal notranslate"><span class="pre">floor()</span></code></a> 和 <a class="reference internal" href="../library/math.html#math.ceil" title="math.ceil"><code class="xref py py-func docutils literal notranslate"><span class="pre">ceil()</span></code></a>。 除了将 <em>ndigits</em> 传给 <code class="xref py py-meth docutils literal notranslate"><span class="pre">__round__()</span></code> 的情况之外这些方法的返回值都应当是原对象截断为 <a class="reference internal" href="../library/numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code></a> (通常为 <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>)。</p>
|
||
<p>如果 <a class="reference internal" href="#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a> 或 <a class="reference internal" href="#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> 均未被定义则内置函数 <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> 会回退至 <a class="reference internal" href="#object.__trunc__" title="object.__trunc__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__trunc__()</span></code></a>。</p>
|
||
</dd></dl>
|
||
|
||
</section>
|
||
<section id="with-statement-context-managers">
|
||
<span id="context-managers"></span><h3><span class="section-number">3.3.9. </span>with 语句上下文管理器<a class="headerlink" href="#with-statement-context-managers" title="永久链接至标题">¶</a></h3>
|
||
<p><em class="dfn">上下文管理器</em> 是一个对象,它定义了在执行 <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> 语句时要建立的运行时上下文。 上下文管理器处理进入和退出所需运行时上下文以执行代码块。 通常使用 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> 语句(在 <a class="reference internal" href="compound_stmts.html#with"><span class="std std-ref">with 语句</span></a> 中描述),但是也可以通过直接调用它们的方法来使用。</p>
|
||
<p id="index-102">上下文管理器的典型用法包括保存和恢复各种全局状态,锁定和解锁资源,关闭打开的文件等等。</p>
|
||
<p>要了解上下文管理器的更多信息,请参阅 <a class="reference internal" href="../library/stdtypes.html#typecontextmanager"><span class="std std-ref">上下文管理器类型</span></a>。</p>
|
||
<dl class="method">
|
||
<dt id="object.__enter__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__enter__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__enter__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>进入与此对象相关的运行时上下文。 <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> 语句将会绑定这个方法的返回值到 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> 子句中指定的目标,如果有的话。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__exit__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__exit__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">exc_type</em>, <em class="sig-param">exc_value</em>, <em class="sig-param">traceback</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__exit__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>退出关联到此对象的运行时上下文。 各个参数描述了导致上下文退出的异常。 如果上下文是无异常地退出的,三个参数都将为 <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>。</p>
|
||
<p>如果提供了异常,并且希望方法屏蔽此异常(即避免其被传播),则应当返回真值。 否则的话,异常将在退出此方法时按正常流程处理。</p>
|
||
<p>请注意 <a class="reference internal" href="#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> 方法不应该重新引发被传入的异常,这是调用者的责任。</p>
|
||
</dd></dl>
|
||
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">参见</p>
|
||
<dl class="simple">
|
||
<dt><span class="target" id="index-126"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - "with" 语句</dt><dd><p>Python <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> 语句的规范描述、背景和示例。</p>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</section>
|
||
<section id="special-method-lookup">
|
||
<span id="special-lookup"></span><h3><span class="section-number">3.3.10. </span>特殊方法查找<a class="headerlink" href="#special-method-lookup" title="永久链接至标题">¶</a></h3>
|
||
<p>对于自定义类来说,特殊方法的隐式发起调用仅保证在其定义于对象类型中时能正确地发挥作用,而不能定义在对象实例字典中。 该行为就是以下代码会引发异常的原因。:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
|
||
<span class="gp">... </span> <span class="k">pass</span>
|
||
<span class="gp">...</span>
|
||
<span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
|
||
<span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="fm">__len__</span> <span class="o">=</span> <span class="k">lambda</span><span class="p">:</span> <span class="mi">5</span>
|
||
<span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
|
||
<span class="gt">Traceback (most recent call last):</span>
|
||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||
<span class="gr">TypeError</span>: <span class="n">object of type 'C' has no len()</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>此行为背后的原理在于包括类型对象在内的所有对象都会实现的几个特殊方法,例如 <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> 和 <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a>。 如果这些方法的隐式查找使用了传统的查找过程,它们会在对类型对象本身发起调用时失败:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mi">1</span> <span class="o">.</span><span class="fm">__hash__</span><span class="p">()</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
|
||
<span class="go">True</span>
|
||
<span class="gp">>>> </span><span class="nb">int</span><span class="o">.</span><span class="fm">__hash__</span><span class="p">()</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
|
||
<span class="gt">Traceback (most recent call last):</span>
|
||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||
<span class="gr">TypeError</span>: <span class="n">descriptor '__hash__' of 'int' object needs an argument</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>以这种方式不正确地尝试发起调用一个类的未绑定方法有时被称为‘元类混淆’,可以通过在查找特殊方法时绕过实例的方式来避免:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">type</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="fm">__hash__</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
|
||
<span class="go">True</span>
|
||
<span class="gp">>>> </span><span class="nb">type</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span><span class="o">.</span><span class="fm">__hash__</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
|
||
<span class="go">True</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>除了为了正确性而绕过任何实例属性之外,隐式特殊方法查找通常也会绕过 <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> 方法,甚至包括对象的元类:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
|
||
<span class="gp">... </span> <span class="k">def</span> <span class="fm">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
|
||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Metaclass getattribute invoked"</span><span class="p">)</span>
|
||
<span class="gp">... </span> <span class="k">return</span> <span class="nb">type</span><span class="o">.</span><span class="fm">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
|
||
<span class="gp">...</span>
|
||
<span class="gp">>>> </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">,</span> <span class="n">metaclass</span><span class="o">=</span><span class="n">Meta</span><span class="p">):</span>
|
||
<span class="gp">... </span> <span class="k">def</span> <span class="fm">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||
<span class="gp">... </span> <span class="k">return</span> <span class="mi">10</span>
|
||
<span class="gp">... </span> <span class="k">def</span> <span class="fm">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
|
||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Class getattribute invoked"</span><span class="p">)</span>
|
||
<span class="gp">... </span> <span class="k">return</span> <span class="nb">object</span><span class="o">.</span><span class="fm">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
|
||
<span class="gp">...</span>
|
||
<span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
|
||
<span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="fm">__len__</span><span class="p">()</span> <span class="c1"># Explicit lookup via instance</span>
|
||
<span class="go">Class getattribute invoked</span>
|
||
<span class="go">10</span>
|
||
<span class="gp">>>> </span><span class="nb">type</span><span class="p">(</span><span class="n">c</span><span class="p">)</span><span class="o">.</span><span class="fm">__len__</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c1"># Explicit lookup via type</span>
|
||
<span class="go">Metaclass getattribute invoked</span>
|
||
<span class="go">10</span>
|
||
<span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c1"># Implicit lookup</span>
|
||
<span class="go">10</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>以这种方式绕过 <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> 机制为解析器内部的速度优化提供了显著的空间,其代价则是牺牲了处理特殊方法时的一些灵活性(特殊方法 <em>必须</em> 设置在类对象本身上以便始终一致地由解释器发起调用)。</p>
|
||
</section>
|
||
</section>
|
||
<section id="coroutines">
|
||
<span id="index-104"></span><h2><span class="section-number">3.4. </span>协程<a class="headerlink" href="#coroutines" title="永久链接至标题">¶</a></h2>
|
||
<section id="awaitable-objects">
|
||
<h3><span class="section-number">3.4.1. </span>可等待对象<a class="headerlink" href="#awaitable-objects" title="永久链接至标题">¶</a></h3>
|
||
<p><a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> 对象主要实现了 <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code></a> 方法。 从 <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> 函数返回的 <a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">协程对象</span></a> 即属于可等待对象。</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">注解</p>
|
||
<p>从带有 <a class="reference internal" href="../library/types.html#types.coroutine" title="types.coroutine"><code class="xref py py-func docutils literal notranslate"><span class="pre">types.coroutine()</span></code></a> 或 <a class="reference internal" href="../library/asyncio-task.html#asyncio.coroutine" title="asyncio.coroutine"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.coroutine()</span></code></a> 装饰器的生成器返回的 <a class="reference internal" href="../glossary.html#term-generator-iterator"><span class="xref std std-term">generator iterator</span></a> 对象也属于可等待对象,但它们并未实现 <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code></a>。</p>
|
||
</div>
|
||
<dl class="method">
|
||
<dt id="object.__await__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__await__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__await__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>必须返回一个 <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>。 应当被用来实现 <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> 对象。 例如,<a class="reference internal" href="../library/asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a> 实现了此方法以与 <a class="reference internal" href="expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> 表达式相兼容。</p>
|
||
</dd></dl>
|
||
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">3.5 新版功能.</span></p>
|
||
</div>
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">参见</p>
|
||
<p><span class="target" id="index-127"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0492"><strong>PEP 492</strong></a> 了解有关可等待对象的详细信息。</p>
|
||
</div>
|
||
</section>
|
||
<section id="coroutine-objects">
|
||
<span id="id7"></span><h3><span class="section-number">3.4.2. </span>协程对象<a class="headerlink" href="#coroutine-objects" title="永久链接至标题">¶</a></h3>
|
||
<p><a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">协程对象</span></a> 属于 <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> 对象。 协程的执行可通过调用 <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code></a> 并迭代其结果来控制。 当协程结束执行并返回时,迭代器会引发 <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>,该异常的 <code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code> 属性将存放返回值。 如果协程引发了异常,它会被迭代器所传播。 协程不应直接引发未处理的 <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> 异常。</p>
|
||
<p>协程也具有下面列出的方法,它们类似于生成器的对应方法 (参见 <a class="reference internal" href="expressions.html#generator-methods"><span class="std std-ref">生成器-迭代器的方法</span></a>)。 但是,与生成器不同,协程并不直接支持迭代。</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">在 3.5.2 版更改: </span>等待一个协程超过一次将引发 <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>。</p>
|
||
</div>
|
||
<dl class="method">
|
||
<dt id="coroutine.send">
|
||
<code class="sig-prename descclassname">coroutine.</code><code class="sig-name descname">send</code><span class="sig-paren">(</span><em class="sig-param">value</em><span class="sig-paren">)</span><a class="headerlink" href="#coroutine.send" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>开始或恢复协程的执行。 如果 <em>value</em> 为 <code class="docutils literal notranslate"><span class="pre">None</span></code>,则这相当于前往 <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code></a> 所返回迭代器的下一项。 如果 <em>value</em> 不为 <code class="docutils literal notranslate"><span class="pre">None</span></code>,此方法将委托给导致协程挂起的迭代器的 <a class="reference internal" href="expressions.html#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> 方法。 其结果(返回值,<a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> 或是其他异常)将与上述对 <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code></a> 返回值进行迭代的结果相同。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="coroutine.throw">
|
||
<code class="sig-prename descclassname">coroutine.</code><code class="sig-name descname">throw</code><span class="sig-paren">(</span><em class="sig-param">type</em><span class="optional">[</span>, <em class="sig-param">value</em><span class="optional">[</span>, <em class="sig-param">traceback</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#coroutine.throw" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>在协程内引发指定的异常。 此方法将委托给导致协程挂起的迭代器的 <a class="reference internal" href="expressions.html#generator.throw" title="generator.throw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">throw()</span></code></a> 方法,如果存在该方法。 否则的话,异常会在挂起点被引发。 其结果(返回值,<a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> 或是其他异常)将与上述对 <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code></a> 返回值进行迭代的结果相同。 如果异常未在协程内被捕获,则将回传给调用者。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="coroutine.close">
|
||
<code class="sig-prename descclassname">coroutine.</code><code class="sig-name descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#coroutine.close" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>此方法会使得协程清理自身并退出。 如果协程被挂起,此方法会先委托给导致协程挂起的迭代器的 <a class="reference internal" href="expressions.html#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> 方法,如果存在该方法。 然后它会在挂起点引发 <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a>,使得协程立即清理自身。 最后,协程会被标记为已结束执行,即使它根本未被启动。</p>
|
||
<p>当协程对象将要被销毁时,会使用以上处理过程来自动关闭。</p>
|
||
</dd></dl>
|
||
|
||
</section>
|
||
<section id="asynchronous-iterators">
|
||
<span id="async-iterators"></span><h3><span class="section-number">3.4.3. </span>异步迭代器<a class="headerlink" href="#asynchronous-iterators" title="永久链接至标题">¶</a></h3>
|
||
<p><em>异步迭代器</em> 可以在其 <code class="docutils literal notranslate"><span class="pre">__anext__</span></code> 方法中调用异步代码。</p>
|
||
<p>异步迭代器可在 <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> 语句中使用。</p>
|
||
<dl class="method">
|
||
<dt id="object.__aiter__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__aiter__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__aiter__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>必须返回一个 <em>异步迭代器</em> 对象。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__anext__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__anext__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__anext__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>必须返回一个 <em>可等待对象</em> 输出迭代器的下一结果值。 当迭代结束时应该引发 <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> 错误。</p>
|
||
</dd></dl>
|
||
|
||
<p>异步可迭代对象的一个示例:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Reader</span><span class="p">:</span>
|
||
<span class="k">async</span> <span class="k">def</span> <span class="nf">readline</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||
<span class="o">...</span>
|
||
|
||
<span class="k">def</span> <span class="fm">__aiter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||
<span class="k">return</span> <span class="bp">self</span>
|
||
|
||
<span class="k">async</span> <span class="k">def</span> <span class="fm">__anext__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||
<span class="n">val</span> <span class="o">=</span> <span class="k">await</span> <span class="bp">self</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
|
||
<span class="k">if</span> <span class="n">val</span> <span class="o">==</span> <span class="sa">b</span><span class="s1">''</span><span class="p">:</span>
|
||
<span class="k">raise</span> <span class="ne">StopAsyncIteration</span>
|
||
<span class="k">return</span> <span class="n">val</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">3.5 新版功能.</span></p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">在 3.7 版更改: </span>在 Python 3.7 之前,<code class="docutils literal notranslate"><span class="pre">__aiter__</span></code> 可以返回一个 <em>可迭代对象</em> 并解析为 <a class="reference internal" href="../glossary.html#term-asynchronous-iterator"><span class="xref std std-term">异步迭代器</span></a>。</p>
|
||
<p>从 Python 3.7 开始,<code class="docutils literal notranslate"><span class="pre">__aiter__</span></code> 必须 返回一个异步迭代器对象。 返回任何其他对象都将导致 <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> 错误。</p>
|
||
</div>
|
||
</section>
|
||
<section id="asynchronous-context-managers">
|
||
<span id="async-context-managers"></span><h3><span class="section-number">3.4.4. </span>异步上下文管理器<a class="headerlink" href="#asynchronous-context-managers" title="永久链接至标题">¶</a></h3>
|
||
<p><em>异步上下文管理器</em> 是 <em>上下文管理器</em> 的一种,它能够在其 <code class="docutils literal notranslate"><span class="pre">__aenter__</span></code> 和 <code class="docutils literal notranslate"><span class="pre">__aexit__</span></code> 方法中暂停执行。</p>
|
||
<p>异步上下文管理器可在 <a class="reference internal" href="compound_stmts.html#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a> 语句中使用。</p>
|
||
<dl class="method">
|
||
<dt id="object.__aenter__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__aenter__</code><span class="sig-paren">(</span><em class="sig-param">self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__aenter__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>在语义上类似于 <a class="reference internal" href="#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a>,仅有的区别是它必须返回一个 <em>可等待对象</em>。</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="object.__aexit__">
|
||
<code class="sig-prename descclassname">object.</code><code class="sig-name descname">__aexit__</code><span class="sig-paren">(</span><em class="sig-param">self</em>, <em class="sig-param">exc_type</em>, <em class="sig-param">exc_value</em>, <em class="sig-param">traceback</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__aexit__" title="永久链接至目标">¶</a></dt>
|
||
<dd><p>在语义上类似于 <a class="reference internal" href="#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>,仅有的区别是它必须返回一个 <em>可等待对象</em>。</p>
|
||
</dd></dl>
|
||
|
||
<p>异步上下文管理器类的一个示例:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">AsyncContextManager</span><span class="p">:</span>
|
||
<span class="k">async</span> <span class="k">def</span> <span class="fm">__aenter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||
<span class="k">await</span> <span class="n">log</span><span class="p">(</span><span class="s1">'entering context'</span><span class="p">)</span>
|
||
|
||
<span class="k">async</span> <span class="k">def</span> <span class="fm">__aexit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">exc_type</span><span class="p">,</span> <span class="n">exc</span><span class="p">,</span> <span class="n">tb</span><span class="p">):</span>
|
||
<span class="k">await</span> <span class="n">log</span><span class="p">(</span><span class="s1">'exiting context'</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">3.5 新版功能.</span></p>
|
||
</div>
|
||
<p class="rubric">备注</p>
|
||
<dl class="footnote brackets">
|
||
<dt class="label" id="id8"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
|
||
<dd><p>在某些情况下 <em>有可能</em> 基于可控的条件改变一个对象的类型。 但这通常不是个好主意,因为如果处理不当会导致一些非常怪异的行为。</p>
|
||
</dd>
|
||
<dt class="label" id="id9"><span class="brackets"><a class="fn-backref" href="#id2">2</a></span></dt>
|
||
<dd><p><a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>, <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a> 以及 <a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> 方法对此有特殊处理;其他方法仍会引发 <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>,但可能依靠 <code class="docutils literal notranslate"><span class="pre">None</span></code> 属于不可调用对象的行为来做到这一点。</p>
|
||
</dd>
|
||
<dt class="label" id="id10"><span class="brackets"><a class="fn-backref" href="#id5">3</a></span></dt>
|
||
<dd><p>这里的“不支持”是指该类无此方法,或方法返回 <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>。 如果你想强制回退到右操作数的反射方法,请不要设置方法为 <code class="docutils literal notranslate"><span class="pre">None</span></code> — 那会造成显式地 <em>阻塞</em> 此种回退的相反效果。</p>
|
||
</dd>
|
||
<dt class="label" id="id11"><span class="brackets"><a class="fn-backref" href="#id6">4</a></span></dt>
|
||
<dd><p>对于相同类型的操作数,如果非反射方法 -- 例如 <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a> -- 失败则会认为整个运算都不被支持,这就是反射方法未被调用的原因。</p>
|
||
</dd>
|
||
</dl>
|
||
</section>
|
||
</section>
|
||
</section>
|
||
|
||
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
|
||
<div class="sphinxsidebarwrapper">
|
||
<h3><a href="../contents.html">目录</a></h3>
|
||
<ul>
|
||
<li><a class="reference internal" href="#">3. 数据模型</a><ul>
|
||
<li><a class="reference internal" href="#objects-values-and-types">3.1. 对象、值与类型</a></li>
|
||
<li><a class="reference internal" href="#the-standard-type-hierarchy">3.2. 标准类型层级结构</a></li>
|
||
<li><a class="reference internal" href="#special-method-names">3.3. 特殊方法名称</a><ul>
|
||
<li><a class="reference internal" href="#basic-customization">3.3.1. 基本定制</a></li>
|
||
<li><a class="reference internal" href="#customizing-attribute-access">3.3.2. 自定义属性访问</a><ul>
|
||
<li><a class="reference internal" href="#customizing-module-attribute-access">3.3.2.1. 自定义模块属性访问</a></li>
|
||
<li><a class="reference internal" href="#implementing-descriptors">3.3.2.2. 实现描述器</a></li>
|
||
<li><a class="reference internal" href="#invoking-descriptors">3.3.2.3. 调用描述器</a></li>
|
||
<li><a class="reference internal" href="#slots">3.3.2.4. __slots__</a><ul>
|
||
<li><a class="reference internal" href="#notes-on-using-slots">3.3.2.4.1. 使用 <em>__slots__</em> 的注意事项</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#customizing-class-creation">3.3.3. 自定义类创建</a><ul>
|
||
<li><a class="reference internal" href="#metaclasses">3.3.3.1. 元类</a></li>
|
||
<li><a class="reference internal" href="#resolving-mro-entries">3.3.3.2. 解析 MRO 条目</a></li>
|
||
<li><a class="reference internal" href="#determining-the-appropriate-metaclass">3.3.3.3. 确定适当的元类</a></li>
|
||
<li><a class="reference internal" href="#preparing-the-class-namespace">3.3.3.4. 准备类命名空间</a></li>
|
||
<li><a class="reference internal" href="#executing-the-class-body">3.3.3.5. 执行类主体</a></li>
|
||
<li><a class="reference internal" href="#creating-the-class-object">3.3.3.6. 创建类对象</a></li>
|
||
<li><a class="reference internal" href="#uses-for-metaclasses">3.3.3.7. 元类的作用</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#customizing-instance-and-subclass-checks">3.3.4. 自定义实例及子类检查</a></li>
|
||
<li><a class="reference internal" href="#emulating-generic-types">3.3.5. 模拟泛型类型</a></li>
|
||
<li><a class="reference internal" href="#emulating-callable-objects">3.3.6. 模拟可调用对象</a></li>
|
||
<li><a class="reference internal" href="#emulating-container-types">3.3.7. 模拟容器类型</a></li>
|
||
<li><a class="reference internal" href="#emulating-numeric-types">3.3.8. 模拟数字类型</a></li>
|
||
<li><a class="reference internal" href="#with-statement-context-managers">3.3.9. with 语句上下文管理器</a></li>
|
||
<li><a class="reference internal" href="#special-method-lookup">3.3.10. 特殊方法查找</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#coroutines">3.4. 协程</a><ul>
|
||
<li><a class="reference internal" href="#awaitable-objects">3.4.1. 可等待对象</a></li>
|
||
<li><a class="reference internal" href="#coroutine-objects">3.4.2. 协程对象</a></li>
|
||
<li><a class="reference internal" href="#asynchronous-iterators">3.4.3. 异步迭代器</a></li>
|
||
<li><a class="reference internal" href="#asynchronous-context-managers">3.4.4. 异步上下文管理器</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
|
||
<h4>上一个主题</h4>
|
||
<p class="topless"><a href="lexical_analysis.html"
|
||
title="上一章"><span class="section-number">2. </span>词法分析</a></p>
|
||
<h4>下一个主题</h4>
|
||
<p class="topless"><a href="executionmodel.html"
|
||
title="下一章"><span class="section-number">4. </span>执行模型</a></p>
|
||
<div role="note" aria-label="source link">
|
||
<h3>本页</h3>
|
||
<ul class="this-page-menu">
|
||
<li><a href="../bugs.html">报告 Bug</a></li>
|
||
<li>
|
||
<a href="https://github.com/python/cpython/blob/3.8/Doc/reference/datamodel.rst"
|
||
rel="nofollow">显示源代码
|
||
</a>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="clearer"></div>
|
||
</div>
|
||
<div class="related" role="navigation" aria-label="related navigation">
|
||
<h3>导航</h3>
|
||
<ul>
|
||
<li class="right" style="margin-right: 10px">
|
||
<a href="../genindex.html" title="总目录"
|
||
>索引</a></li>
|
||
<li class="right" >
|
||
<a href="../py-modindex.html" title="Python 模块索引"
|
||
>模块</a> |</li>
|
||
<li class="right" >
|
||
<a href="executionmodel.html" title="4. 执行模型"
|
||
>下一页</a> |</li>
|
||
<li class="right" >
|
||
<a href="lexical_analysis.html" title="2. 词法分析"
|
||
>上一页</a> |</li>
|
||
|
||
<li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||
<li class="switchers">
|
||
<div class="language_switcher_placeholder"></div>
|
||
<div class="version_switcher_placeholder"></div>
|
||
</li>
|
||
<li>
|
||
|
||
</li>
|
||
<li id="cpython-language-and-version">
|
||
<a href="../index.html">3.8.20 Documentation</a> »
|
||
</li>
|
||
|
||
<li class="nav-item nav-item-1"><a href="index.html" >Python语言参考</a> »</li>
|
||
<li class="right">
|
||
|
||
|
||
<div class="inline-search" role="search">
|
||
<form class="inline-search" action="../search.html" method="get">
|
||
<input placeholder="快速搜索" aria-label="快速搜索" type="text" name="q" />
|
||
<input type="submit" value="转向" />
|
||
<input type="hidden" name="check_keywords" value="yes" />
|
||
<input type="hidden" name="area" value="default" />
|
||
</form>
|
||
</div>
|
||
|
|
||
</li>
|
||
|
||
</ul>
|
||
</div>
|
||
<div class="footer">
|
||
© <a href="../copyright.html">版权所有</a> 2001-2024, Python Software Foundation.
|
||
<br />
|
||
This page is licensed under the Python Software Foundation License Version 2.
|
||
<br />
|
||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||
<br />
|
||
|
||
<br />
|
||
|
||
The Python Software Foundation is a non-profit corporation.
|
||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||
<br />
|
||
<br />
|
||
|
||
最后更新于 12月 09, 2024.
|
||
<a href="https://docs.python.org/3/bugs.html">Found a bug</a>?
|
||
<br />
|
||
|
||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 2.4.4.
|
||
</div>
|
||
|
||
</body>
|
||
</html> |