1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
5
<html xmlns="http://www.w3.org/1999/xhtml">
7
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
9
<title>28.8. abc — Abstract Base Classes — Python 2.7.12 documentation</title>
11
<link rel="stylesheet" href="../_static/classic.css" type="text/css" />
12
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
14
<script type="text/javascript">
15
var DOCUMENTATION_OPTIONS = {
18
COLLAPSE_INDEX: false,
23
<script type="text/javascript" src="../_static/jquery.js"></script>
24
<script type="text/javascript" src="../_static/underscore.js"></script>
25
<script type="text/javascript" src="../_static/doctools.js"></script>
26
<script type="text/javascript" src="../_static/sidebar.js"></script>
27
<link rel="search" type="application/opensearchdescription+xml"
28
title="Search within Python 2.7.12 documentation"
29
href="../_static/opensearch.xml"/>
30
<link rel="author" title="About these documents" href="../about.html" />
31
<link rel="copyright" title="Copyright" href="../copyright.html" />
32
<link rel="top" title="Python 2.7.12 documentation" href="../contents.html" />
33
<link rel="up" title="28. Python Runtime Services" href="python.html" />
34
<link rel="next" title="28.9. atexit — Exit handlers" href="atexit.html" />
35
<link rel="prev" title="28.7. contextlib — Utilities for with-statement contexts" href="contextlib.html" />
36
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
37
<script type="text/javascript" src="../_static/copybutton.js"></script>
38
<script type="text/javascript" src="../_static/version_switch.js"></script>
43
<body role="document">
44
<div class="related" role="navigation" aria-label="related navigation">
47
<li class="right" style="margin-right: 10px">
48
<a href="../genindex.html" title="General Index"
49
accesskey="I">index</a></li>
51
<a href="../py-modindex.html" title="Python Module Index"
54
<a href="atexit.html" title="28.9. atexit — Exit handlers"
55
accesskey="N">next</a> |</li>
57
<a href="contextlib.html" title="28.7. contextlib — Utilities for with-statement contexts"
58
accesskey="P">previous</a> |</li>
59
<li><img src="../_static/py.png" alt=""
60
style="vertical-align: middle; margin-top: -1px"/></li>
61
<li><a href="https://www.python.org/">Python</a> »</li>
63
<span class="version_switcher_placeholder">2.7.12</span>
64
<a href="../index.html">Documentation</a> »
67
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>
68
<li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> »</li>
72
<div class="document">
73
<div class="documentwrapper">
74
<div class="bodywrapper">
75
<div class="body" role="main">
77
<div class="section" id="module-abc">
78
<span id="abc-abstract-base-classes"></span><h1>28.8. <a class="reference internal" href="#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal"><span class="pre">abc</span></code></a> — Abstract Base Classes<a class="headerlink" href="#module-abc" title="Permalink to this headline">¶</a></h1>
79
<div class="versionadded">
80
<p><span class="versionmodified">New in version 2.6.</span></p>
82
<p><strong>Source code:</strong> <a class="reference external" href="https://hg.python.org/cpython/file/2.7/Lib/abc.py">Lib/abc.py</a></p>
83
<hr class="docutils" />
84
<p>This module provides the infrastructure for defining <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base
85
classes</span></a> (ABCs) in Python, as outlined in <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a>; see the PEP for why this
86
was added to Python. (See also <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3141"><strong>PEP 3141</strong></a> and the <a class="reference internal" href="numbers.html#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal"><span class="pre">numbers</span></code></a> module
87
regarding a type hierarchy for numbers based on ABCs.)</p>
88
<p>The <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal"><span class="pre">collections</span></code></a> module has some concrete classes that derive from
89
ABCs; these can, of course, be further derived. In addition the
90
<a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal"><span class="pre">collections</span></code></a> module has some ABCs that can be used to test whether
91
a class or instance provides a particular interface, for example, is it
92
hashable or a mapping.</p>
93
<p>This module provides the following class:</p>
96
<em class="property">class </em><code class="descclassname">abc.</code><code class="descname">ABCMeta</code><a class="headerlink" href="#abc.ABCMeta" title="Permalink to this definition">¶</a></dt>
97
<dd><p>Metaclass for defining Abstract Base Classes (ABCs).</p>
98
<p>Use this metaclass to create an ABC. An ABC can be subclassed directly, and
99
then acts as a mix-in class. You can also register unrelated concrete
100
classes (even built-in classes) and unrelated ABCs as “virtual subclasses” –
101
these and their descendants will be considered subclasses of the registering
102
ABC by the built-in <a class="reference internal" href="functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal"><span class="pre">issubclass()</span></code></a> function, but the registering ABC
103
won’t show up in their MRO (Method Resolution Order) nor will method
104
implementations defined by the registering ABC be callable (not even via
105
<a class="reference internal" href="functions.html#super" title="super"><code class="xref py py-func docutils literal"><span class="pre">super()</span></code></a>). <a class="footnote-reference" href="#id2" id="id1">[1]</a></p>
106
<p>Classes created with a metaclass of <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal"><span class="pre">ABCMeta</span></code></a> have the following method:</p>
108
<dt id="abc.ABCMeta.register">
109
<code class="descname">register</code><span class="sig-paren">(</span><em>subclass</em><span class="sig-paren">)</span><a class="headerlink" href="#abc.ABCMeta.register" title="Permalink to this definition">¶</a></dt>
110
<dd><p>Register <em>subclass</em> as a “virtual subclass” of this ABC. For
112
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">abc</span> <span class="kn">import</span> <span class="n">ABCMeta</span>
114
<span class="k">class</span> <span class="nc">MyABC</span><span class="p">:</span>
115
<span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>
117
<span class="n">MyABC</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">tuple</span><span class="p">)</span>
119
<span class="k">assert</span> <span class="nb">issubclass</span><span class="p">(</span><span class="nb">tuple</span><span class="p">,</span> <span class="n">MyABC</span><span class="p">)</span>
120
<span class="k">assert</span> <span class="nb">isinstance</span><span class="p">((),</span> <span class="n">MyABC</span><span class="p">)</span>
125
<p>You can also override this method in an abstract base class:</p>
127
<dt id="abc.ABCMeta.__subclasshook__">
128
<code class="descname">__subclasshook__</code><span class="sig-paren">(</span><em>subclass</em><span class="sig-paren">)</span><a class="headerlink" href="#abc.ABCMeta.__subclasshook__" title="Permalink to this definition">¶</a></dt>
129
<dd><p>(Must be defined as a class method.)</p>
130
<p>Check whether <em>subclass</em> is considered a subclass of this ABC. This means
131
that you can customize the behavior of <code class="docutils literal"><span class="pre">issubclass</span></code> further without the
132
need to call <a class="reference internal" href="#abc.ABCMeta.register" title="abc.ABCMeta.register"><code class="xref py py-meth docutils literal"><span class="pre">register()</span></code></a> on every class you want to consider a
133
subclass of the ABC. (This class method is called from the
134
<code class="xref py py-meth docutils literal"><span class="pre">__subclasscheck__()</span></code> method of the ABC.)</p>
135
<p>This method should return <code class="docutils literal"><span class="pre">True</span></code>, <code class="docutils literal"><span class="pre">False</span></code> or <code class="docutils literal"><span class="pre">NotImplemented</span></code>. If
136
it returns <code class="docutils literal"><span class="pre">True</span></code>, the <em>subclass</em> is considered a subclass of this ABC.
137
If it returns <code class="docutils literal"><span class="pre">False</span></code>, the <em>subclass</em> is not considered a subclass of
138
this ABC, even if it would normally be one. If it returns
139
<code class="docutils literal"><span class="pre">NotImplemented</span></code>, the subclass check is continued with the usual
143
<p>For a demonstration of these concepts, look at this example ABC definition:</p>
144
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
145
<span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">index</span><span class="p">):</span>
146
<span class="o">...</span>
147
<span class="k">def</span> <span class="nf">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
148
<span class="o">...</span>
149
<span class="k">def</span> <span class="nf">get_iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
150
<span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
152
<span class="k">class</span> <span class="nc">MyIterable</span><span class="p">:</span>
153
<span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>
155
<span class="nd">@abstractmethod</span>
156
<span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
157
<span class="k">while</span> <span class="bp">False</span><span class="p">:</span>
158
<span class="k">yield</span> <span class="bp">None</span>
160
<span class="k">def</span> <span class="nf">get_iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
161
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">__iter__</span><span class="p">()</span>
163
<span class="nd">@classmethod</span>
164
<span class="k">def</span> <span class="nf">__subclasshook__</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">C</span><span class="p">):</span>
165
<span class="k">if</span> <span class="n">cls</span> <span class="ow">is</span> <span class="n">MyIterable</span><span class="p">:</span>
166
<span class="k">if</span> <span class="nb">any</span><span class="p">(</span><span class="s2">"__iter__"</span> <span class="ow">in</span> <span class="n">B</span><span class="o">.</span><span class="n">__dict__</span> <span class="k">for</span> <span class="n">B</span> <span class="ow">in</span> <span class="n">C</span><span class="o">.</span><span class="n">__mro__</span><span class="p">):</span>
167
<span class="k">return</span> <span class="bp">True</span>
168
<span class="k">return</span> <span class="bp">NotImplemented</span>
170
<span class="n">MyIterable</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Foo</span><span class="p">)</span>
173
<p>The ABC <code class="docutils literal"><span class="pre">MyIterable</span></code> defines the standard iterable method,
174
<a class="reference internal" href="stdtypes.html#iterator.__iter__" title="iterator.__iter__"><code class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></code></a>, as an abstract method. The implementation given
175
here can still be called from subclasses. The <code class="xref py py-meth docutils literal"><span class="pre">get_iterator()</span></code> method
176
is also part of the <code class="docutils literal"><span class="pre">MyIterable</span></code> abstract base class, but it does not have
177
to be overridden in non-abstract derived classes.</p>
178
<p>The <a class="reference internal" href="#abc.ABCMeta.__subclasshook__" title="abc.ABCMeta.__subclasshook__"><code class="xref py py-meth docutils literal"><span class="pre">__subclasshook__()</span></code></a> class method defined here says that any class
179
that has an <a class="reference internal" href="stdtypes.html#iterator.__iter__" title="iterator.__iter__"><code class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></code></a> method in its
180
<a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a> (or in that of one of its base classes, accessed
181
via the <a class="reference internal" href="stdtypes.html#class.__mro__" title="class.__mro__"><code class="xref py py-attr docutils literal"><span class="pre">__mro__</span></code></a> list) is considered a <code class="docutils literal"><span class="pre">MyIterable</span></code> too.</p>
182
<p>Finally, the last line makes <code class="docutils literal"><span class="pre">Foo</span></code> a virtual subclass of <code class="docutils literal"><span class="pre">MyIterable</span></code>,
183
even though it does not define an <a class="reference internal" href="stdtypes.html#iterator.__iter__" title="iterator.__iter__"><code class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></code></a> method (it uses
184
the old-style iterable protocol, defined in terms of <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal"><span class="pre">__len__()</span></code></a> and
185
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>). Note that this will not make <code class="docutils literal"><span class="pre">get_iterator</span></code>
186
available as a method of <code class="docutils literal"><span class="pre">Foo</span></code>, so it is provided separately.</p>
189
<p>It also provides the following decorators:</p>
190
<dl class="function">
191
<dt id="abc.abstractmethod">
192
<code class="descclassname">abc.</code><code class="descname">abstractmethod</code><span class="sig-paren">(</span><em>function</em><span class="sig-paren">)</span><a class="headerlink" href="#abc.abstractmethod" title="Permalink to this definition">¶</a></dt>
193
<dd><p>A decorator indicating abstract methods.</p>
194
<p>Using this decorator requires that the class’s metaclass is <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal"><span class="pre">ABCMeta</span></code></a> or
196
A class that has a metaclass derived from <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal"><span class="pre">ABCMeta</span></code></a>
197
cannot be instantiated unless all of its abstract methods and
198
properties are overridden.
199
The abstract methods can be called using any of the normal ‘super’ call
201
<p>Dynamically adding abstract methods to a class, or attempting to modify the
202
abstraction status of a method or class once it is created, are not
203
supported. The <a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal"><span class="pre">abstractmethod()</span></code></a> only affects subclasses derived using
204
regular inheritance; “virtual subclasses” registered with the ABC’s
205
<code class="xref py py-meth docutils literal"><span class="pre">register()</span></code> method are not affected.</p>
207
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
208
<span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>
209
<span class="nd">@abstractmethod</span>
210
<span class="k">def</span> <span class="nf">my_abstract_method</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">...</span><span class="p">):</span>
211
<span class="o">...</span>
214
<div class="admonition note">
215
<p class="first admonition-title">Note</p>
216
<p class="last">Unlike Java abstract methods, these abstract
217
methods may have an implementation. This implementation can be
218
called via the <a class="reference internal" href="functions.html#super" title="super"><code class="xref py py-func docutils literal"><span class="pre">super()</span></code></a> mechanism from the class that
219
overrides it. This could be useful as an end-point for a
220
super-call in a framework that uses cooperative
221
multiple-inheritance.</p>
225
<dl class="function">
226
<dt id="abc.abstractproperty">
227
<code class="descclassname">abc.</code><code class="descname">abstractproperty</code><span class="sig-paren">(</span><span class="optional">[</span><em>fget</em><span class="optional">[</span>, <em>fset</em><span class="optional">[</span>, <em>fdel</em><span class="optional">[</span>, <em>doc</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#abc.abstractproperty" title="Permalink to this definition">¶</a></dt>
228
<dd><p>A subclass of the built-in <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-func docutils literal"><span class="pre">property()</span></code></a>, indicating an abstract property.</p>
229
<p>Using this function requires that the class’s metaclass is <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal"><span class="pre">ABCMeta</span></code></a> or
231
A class that has a metaclass derived from <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal"><span class="pre">ABCMeta</span></code></a> cannot be
232
instantiated unless all of its abstract methods and properties are overridden.
233
The abstract properties can be called using any of the normal
234
‘super’ call mechanisms.</p>
236
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
237
<span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>
238
<span class="nd">@abstractproperty</span>
239
<span class="k">def</span> <span class="nf">my_abstract_property</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
240
<span class="o">...</span>
243
<p>This defines a read-only property; you can also define a read-write abstract
244
property using the ‘long’ form of property declaration:</p>
245
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
246
<span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>
247
<span class="k">def</span> <span class="nf">getx</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="o">...</span>
248
<span class="k">def</span> <span class="nf">setx</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="o">...</span>
249
<span class="n">x</span> <span class="o">=</span> <span class="n">abstractproperty</span><span class="p">(</span><span class="n">getx</span><span class="p">,</span> <span class="n">setx</span><span class="p">)</span>
254
<p class="rubric">Footnotes</p>
255
<table class="docutils footnote" frame="void" id="id2" rules="none">
256
<colgroup><col class="label" /><col /></colgroup>
258
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>C++ programmers should note that Python’s virtual base class
259
concept is not the same as C++’s.</td></tr>
268
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
269
<div class="sphinxsidebarwrapper">
270
<h4>Previous topic</h4>
271
<p class="topless"><a href="contextlib.html"
272
title="previous chapter">28.7. <code class="docutils literal"><span class="pre">contextlib</span></code> — Utilities for <code class="docutils literal"><span class="pre">with</span></code>-statement contexts</a></p>
274
<p class="topless"><a href="atexit.html"
275
title="next chapter">28.9. <code class="docutils literal"><span class="pre">atexit</span></code> — Exit handlers</a></p>
277
<ul class="this-page-menu">
278
<li><a href="../bugs.html">Report a Bug</a></li>
279
<li><a href="../_sources/library/abc.txt"
280
rel="nofollow">Show Source</a></li>
283
<div id="searchbox" style="display: none" role="search">
284
<h3>Quick search</h3>
285
<form class="search" action="../search.html" method="get">
286
<input type="text" name="q" />
287
<input type="submit" value="Go" />
288
<input type="hidden" name="check_keywords" value="yes" />
289
<input type="hidden" name="area" value="default" />
291
<p class="searchtip" style="font-size: 90%">
292
Enter search terms or a module, class or function name.
295
<script type="text/javascript">$('#searchbox').show(0);</script>
298
<div class="clearer"></div>
300
<div class="related" role="navigation" aria-label="related navigation">
303
<li class="right" style="margin-right: 10px">
304
<a href="../genindex.html" title="General Index"
307
<a href="../py-modindex.html" title="Python Module Index"
310
<a href="atexit.html" title="28.9. atexit — Exit handlers"
313
<a href="contextlib.html" title="28.7. contextlib — Utilities for with-statement contexts"
315
<li><img src="../_static/py.png" alt=""
316
style="vertical-align: middle; margin-top: -1px"/></li>
317
<li><a href="https://www.python.org/">Python</a> »</li>
319
<span class="version_switcher_placeholder">2.7.12</span>
320
<a href="../index.html">Documentation</a> »
323
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>
324
<li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> »</li>
328
© <a href="../copyright.html">Copyright</a> 1990-2016, Python Software Foundation.
330
The Python Software Foundation is a non-profit corporation.
331
<a href="https://www.python.org/psf/donations/">Please donate.</a>
333
Last updated on Sep 20, 2016.
334
<a href="../bugs.html">Found a bug</a>?
336
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.3.3.
b'\\ No newline at end of file'