forked from UWPCE-PythonCert/ProgrammingInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubclassingAndInheritance.html
More file actions
383 lines (349 loc) · 30.2 KB
/
Copy pathSubclassingAndInheritance.html
File metadata and controls
383 lines (349 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
<!DOCTYPE html>
<html class="writer-html5" lang="en" data-content_root="../">
<head>
<meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Subclassing and Inheritance — Programming in Python 8.0 documentation</title>
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
<link rel="stylesheet" type="text/css" href="../_static/css/theme.css?v=e59714d7" />
<script src="../_static/jquery.js?v=5d32c60e"></script>
<script src="../_static/_sphinx_javascript_frameworks_compat.js?v=2cd50e6c"></script>
<script src="../_static/documentation_options.js?v=bb3927b2"></script>
<script src="../_static/doctools.js?v=9bcbadda"></script>
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="../_static/js/theme.js"></script>
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="HTML Renderer Exercise" href="../exercises/html_renderer/html_renderer.html" />
<link rel="prev" title="15. Subclassing and Inheritance" href="../topics/15-subclassing/index.html" />
</head>
<body class="wy-body-for-nav">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search" style="background: #4b2e83" >
<a href="../index.html">
</a>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" aria-label="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div><div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
<p class="caption" role="heading"><span class="caption-text">Topics in the Program</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../topics/01-setting_up/index.html">1. Setting up your Environment</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/02-basic_python/index.html">2. Basic Python</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/03-recursion_booleans/index.html">3. Booleans and Recursion</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/04-sequences_iteration/index.html">4. Sequences and Iteration</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/05-text_handling/index.html">5. Basic Text Handling</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/06-exceptions/index.html">6. Exception Handling</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/07-unit_testing/index.html">7. Unit Testing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/08-dicts_sets/index.html">8. Dictionaries and Sets</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/09-files/index.html">9. File Handling</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/10-modules_packages/index.html">10. Modules and Packages</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/11-argument_passing/index.html">11. Advanced Argument Passing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/12-comprehensions/index.html">12. Comprehensions</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/13-intro_oo/index.html">13. Intro to Object Oriented Programing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/14-magic_methods/index.html">14. Properties and Magic Methods</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../topics/15-subclassing/index.html">15. Subclassing and Inheritance</a><ul class="current">
<li class="toctree-l2 current"><a class="current reference internal" href="#">Subclassing and Inheritance</a></li>
<li class="toctree-l2"><a class="reference internal" href="../exercises/html_renderer/html_renderer.html">HTML Renderer Exercise</a></li>
<li class="toctree-l2"><a class="reference internal" href="../exercises/html_renderer/html_renderer_tutorial.html">Tutorial for the Html Render Assignment</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../topics/16-multiple_inheritance/index.html">16. Multiple Inheritance</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/17-functional_programming/index.html">17. Introduction to Functional Programming</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/18-advanced_testing/index.html">18. Advanced Testing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topics/99-extras/index.html">19. Extra Topics</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"><nav class="wy-nav-top" aria-label="Mobile navigation menu" style="background: #4b2e83" >
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../index.html">Programming in Python</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content style-external-links">
<div role="navigation" aria-label="Page navigation">
<ul class="wy-breadcrumbs">
<li><a href="../index.html" class="icon icon-home" aria-label="Home"></a></li>
<li class="breadcrumb-item"><a href="../topics/15-subclassing/index.html"><span class="section-number">15. </span>Subclassing and Inheritance</a></li>
<li class="breadcrumb-item active">Subclassing and Inheritance</li>
<li class="wy-breadcrumbs-aside">
<a href="../_sources/modules/SubclassingAndInheritance.rst.txt" rel="nofollow"> View page source</a>
</li>
</ul><div class="rst-breadcrumbs-buttons" role="navigation" aria-label="Sequential page navigation">
<a href="../topics/15-subclassing/index.html" class="btn btn-neutral float-left" title="15. Subclassing and Inheritance" accesskey="p"><span class="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a>
<a href="../exercises/html_renderer/html_renderer.html" class="btn btn-neutral float-right" title="HTML Renderer Exercise" accesskey="n">Next <span class="fa fa-arrow-circle-right" aria-hidden="true"></span></a>
</div>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<section id="subclassing-and-inheritance">
<span id="subclassing-inheritance"></span><h1>Subclassing and Inheritance<a class="headerlink" href="#subclassing-and-inheritance" title="Link to this heading"></a></h1>
<p>How to put the pieces together to build a complex system without repeating code.</p>
<section id="inheritance">
<h2>Inheritance<a class="headerlink" href="#inheritance" title="Link to this heading"></a></h2>
<p>In object-oriented programming (OOP), inheritance is a way to reuse the code
of existing objects, or to establish a subtype from an existing object.</p>
<p>Objects are defined by classes. Classes can inherit attributes and behavior
from pre-existing classes called base classes or super classes.</p>
<p>The resulting classes are known as derived classes or subclasses.</p>
<p>(<a class="reference external" href="http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29">http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29</a>)</p>
<section id="subclassing">
<h3>Subclassing<a class="headerlink" href="#subclassing" title="Link to this heading"></a></h3>
<p>A subclass “inherits” all the attributes (methods, etc) of the parent class. This means that a subclass will have everything that its “parents” have.</p>
<p>You can then change (“override”) some or all of the attributes to change the behavior. You can also add new attributes to extend the behavior.</p>
<p>You create a subclass by passing the superclass to the <code class="docutils literal notranslate"><span class="pre">class</span></code> statement.</p>
<p>The simplest subclass in Python:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">A_subclass</span><span class="p">(</span><span class="n">The_superclass</span><span class="p">):</span>
<span class="k">pass</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">A_subclass</span></code> now has exactly the same behavior as <code class="docutils literal notranslate"><span class="pre">The_superclass</span></code> – all the same attributes and methods.</p>
</section>
<section id="overriding-attributes">
<h3>Overriding attributes<a class="headerlink" href="#overriding-attributes" title="Link to this heading"></a></h3>
<p>Overriding is as simple as creating a new attribute with the same name:</p>
<div class="highlight-ipython notranslate"><div class="highlight"><pre><span></span><span class="gp">In [1]: </span> <span class="k">class</span><span class="w"> </span><span class="nc">Circle</span><span class="p">:</span>
<span class="gp"> ...: </span> <span class="n">color</span> <span class="o">=</span> <span class="s2">"red"</span>
<span class="gp"> ...:</span>
</pre></div>
</div>
<p>We now have a class with a class attribute, <code class="docutils literal notranslate"><span class="pre">color</span></code>, with the value: “red”. All instances of <code class="docutils literal notranslate"><span class="pre">Circle</span></code> will be red:</p>
<div class="highlight-ipython notranslate"><div class="highlight"><pre><span></span><span class="gp">In [2]: </span><span class="n">c</span> <span class="o">=</span> <span class="n">Circle</span><span class="p">()</span>
<span class="gp">In [3]: </span><span class="n">c</span><span class="o">.</span><span class="n">color</span>
<span class="gh">Out[3]: </span><span class="go">'red'</span>
</pre></div>
</div>
<p>If we create a subclass of Circle, and set that same class attribute:</p>
<div class="highlight-ipython notranslate"><div class="highlight"><pre><span></span><span class="gp">In [4]: </span> <span class="k">class</span><span class="w"> </span><span class="nc">NewCircle</span><span class="p">(</span><span class="n">Circle</span><span class="p">):</span>
<span class="gp"> ...: </span> <span class="n">color</span> <span class="o">=</span> <span class="s2">"blue"</span>
<span class="gp"> ...:</span>
<span class="gp">In [5]: </span><span class="n">nc</span> <span class="o">=</span> <span class="n">NewCircle</span><span class="p">()</span>
<span class="gp">In [6]: </span><span class="n">nc</span><span class="o">.</span><span class="n">color</span>
<span class="gh">Out[6]: </span><span class="go">'blue'</span>
</pre></div>
</div>
<p>We now have a class that is all the same, except that its instances have the color blue.</p>
<p>Note that any methods that refer to that attribute, will get the new value, even if the methods themselves have not changed:</p>
<div class="highlight-ipython notranslate"><div class="highlight"><pre><span></span><span class="gp">In [10]: </span><span class="k">class</span><span class="w"> </span><span class="nc">Circle</span><span class="p">:</span>
<span class="go"> ...: color = "red"</span>
<span class="go"> ...:</span>
<span class="go"> ...: def describe(self):</span>
<span class="go"> ...: return f"I am a {self.color} circle"</span>
<span class="go"> ...:</span>
<span class="gp">In [11]: </span><span class="k">class</span><span class="w"> </span><span class="nc">NewCircle</span><span class="p">(</span><span class="n">Circle</span><span class="p">):</span>
<span class="go"> ...: color = "blue"</span>
<span class="go"> ...:</span>
<span class="gp">In [12]: </span><span class="n">c</span> <span class="o">=</span> <span class="n">Circle</span><span class="p">()</span>
<span class="gp">In [13]: </span><span class="n">c</span><span class="o">.</span><span class="n">describe</span><span class="p">()</span>
<span class="gh">Out[13]: </span><span class="go">'I am a red circle'</span>
<span class="gp">In [14]: </span><span class="n">nc</span> <span class="o">=</span> <span class="n">NewCircle</span><span class="p">()</span>
<span class="gp">In [15]: </span><span class="n">nc</span><span class="o">.</span><span class="n">describe</span><span class="p">()</span>
<span class="gh">Out[15]: </span><span class="go">'I am a blue circle'</span>
</pre></div>
</div>
<p>Note that this is <em>why</em> self is passed in to every method – when you write the method, you don’t know exactly what class <code class="docutils literal notranslate"><span class="pre">self</span></code> will be – it is an instance of the class at the time the method is called.</p>
</section>
<section id="overriding-methods">
<h3>Overriding methods<a class="headerlink" href="#overriding-methods" title="Link to this heading"></a></h3>
<p>Overriding methods is exactly the same thing, but with methods (remember, a method <em>is</em> an attribute in Python – one that happens to be a function)</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">Circle</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">def</span><span class="w"> </span><span class="nf">grow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">factor</span><span class="o">=</span><span class="mi">2</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""grows the circle's diameter by factor"""</span>
<span class="bp">self</span><span class="o">.</span><span class="n">diameter</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">diameter</span> <span class="o">*</span> <span class="n">factor</span>
<span class="o">...</span>
<span class="k">class</span><span class="w"> </span><span class="nc">NewCircle</span><span class="p">(</span><span class="n">Circle</span><span class="p">):</span>
<span class="o">...</span>
<span class="k">def</span><span class="w"> </span><span class="nf">grow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">factor</span><span class="o">=</span><span class="mi">2</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""grows the area by factor..."""</span>
<span class="bp">self</span><span class="o">.</span><span class="n">diameter</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">diameter</span> <span class="o">*</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>all the instances of the new class will have the new method – similar, but different, behavior. Note that both these methods are requiring that the class instance has a <code class="docutils literal notranslate"><span class="pre">diameter</span></code> attribute.</p>
<p><strong>Here’s a program design suggestion:</strong></p>
<blockquote>
<div><p>Whenever you override a method, the interface of the new method should be the same as the old. It should take the same parameters, return the same type, and obey the same preconditions and postconditions.</p>
<p>If you obey this rule, you will find that any function designed to work with an instance of a superclass, like a Deck, will also work with instances of subclasses like a Hand or PokerHand. If you violate this rule, your code will collapse like (sorry) a house of cards.</p>
</div></blockquote>
<p>– from <em>Think Python</em></p>
</section>
<section id="overriding-init">
<h3>Overriding <code class="docutils literal notranslate"><span class="pre">__init__</span></code><a class="headerlink" href="#overriding-init" title="Link to this heading"></a></h3>
<p><code class="docutils literal notranslate"><span class="pre">__init__</span></code> is a common method to override.</p>
<p>You often need to call the super class <code class="docutils literal notranslate"><span class="pre">__init__</span></code> as well, so that any initialization required is performed:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">Circle</span><span class="p">:</span>
<span class="n">color</span> <span class="o">=</span> <span class="s2">"red"</span>
<span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">diameter</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">diameter</span> <span class="o">=</span> <span class="n">diameter</span>
<span class="o">...</span>
<span class="k">class</span><span class="w"> </span><span class="nc">CircleR</span><span class="p">(</span><span class="n">Circle</span><span class="p">):</span>
<span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">radius</span><span class="p">):</span>
<span class="n">diameter</span> <span class="o">=</span> <span class="n">radius</span><span class="o">*</span><span class="mi">2</span>
<span class="n">Circle</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">diameter</span><span class="p">)</span>
</pre></div>
</div>
<p>Exception to: “don’t change the method signature” rule.</p>
<p>Often when you override <code class="docutils literal notranslate"><span class="pre">__init__</span></code>, the new class may take an extra parameter or two. In this case, you will want to keep the signature as similar as possible, and cleanly define what is part of the subclass. A common idiom in this case is this:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">A_Subclass</span><span class="p">(</span><span class="n">A_Superclass</span><span class="p">):</span>
<span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">param1</span><span class="p">,</span> <span class="n">param2</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">param1</span> <span class="o">=</span> <span class="n">param1</span>
<span class="bp">self</span><span class="o">.</span><span class="n">init_something</span><span class="p">(</span><span class="n">param2</span><span class="p">)</span>
<span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>That is:</p>
<blockquote>
<div><ul class="simple">
<li><p>Put the extra parameters in the beginning of the list – usually as required positional parameters.</p></li>
<li><p>Accept <code class="docutils literal notranslate"><span class="pre">*args</span></code> and <code class="docutils literal notranslate"><span class="pre">**kwargs</span></code></p></li>
<li><p>Pass everything else on to the superclass’ __init__</p></li>
</ul>
</div></blockquote>
<p>Using <code class="docutils literal notranslate"><span class="pre">*args</span></code> and <code class="docutils literal notranslate"><span class="pre">**kwargs</span></code> is a way to make it clear that the rest is simply the signature of the superclass. It is also flexible if the superclass (or others up in the hierarchy) changes – it could completely change its signature, and this subclass would still work.</p>
</section>
<section id="using-the-superclass-methods">
<h3>Using the superclass’ methods<a class="headerlink" href="#using-the-superclass-methods" title="Link to this heading"></a></h3>
<p>In a subclass, you can access everything in the superclass: all attributes and other methods:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">Circle</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">def</span><span class="w"> </span><span class="nf">get_area</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">diameter</span><span class="p">):</span>
<span class="k">return</span> <span class="n">math</span><span class="o">.</span><span class="n">pi</span> <span class="o">*</span> <span class="p">(</span><span class="n">diameter</span><span class="o">/</span><span class="mf">2.0</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span>
<span class="k">class</span><span class="w"> </span><span class="nc">CircleR2</span><span class="p">(</span><span class="n">Circle</span><span class="p">):</span>
<span class="o">...</span>
<span class="k">def</span><span class="w"> </span><span class="nf">get_area</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="n">Circle</span><span class="o">.</span><span class="n">get_area</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">radius</span><span class="o">*</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that there is nothing special about <code class="docutils literal notranslate"><span class="pre">__init__</span></code> except that it gets called automatically when you instantiate an instance. Otherwise, it is the same as any other method – it gets <code class="docutils literal notranslate"><span class="pre">self</span></code> as the first argument, it can or can not call the superclass’ methods, etc.</p>
</section>
<section id="favor-object-composition-over-class-inheritance">
<h3>“Favor Object Composition Over Class Inheritance”<a class="headerlink" href="#favor-object-composition-over-class-inheritance" title="Link to this heading"></a></h3>
<p>That is a quotation from the “Design Patterns” book – one of the gospels of OO programming.</p>
<p>But what does it mean?</p>
<p>There are essentially two ways to add multiple functionalities to a class:</p>
<p>Subclassing</p>
<p>and</p>
<p>Composition</p>
<p>As we have just learned about subclassing, you might be tempted to do it a lot. But you need to be careful of over-using subclassing:</p>
<p><a class="reference external" href="https://en.wikipedia.org/wiki/Composition_over_inheritance">https://en.wikipedia.org/wiki/Composition_over_inheritance</a></p>
<p>Composition is when your classes have attributes of various types that they use to gain functionality – “delegate” functionality to – “Delegation” is a related concept in OO.</p>
<section id="is-a-vs-has-a">
<h4>“Is a” vs “Has a”<a class="headerlink" href="#is-a-vs-has-a" title="Link to this heading"></a></h4>
<p>Thinking about “is a” vs “has a” can help you sort this out.</p>
<p>For example, you may have a class that needs to accumulate an arbitrary number of objects.</p>
<p>A list can do that – so maybe you should subclass list?</p>
<p>To help decide – Ask yourself:</p>
<p>– <strong>Is</strong> your class a list (with some extra functionality)?</p>
<p>or</p>
<p>– Does you class <strong>have</strong> a list?</p>
<p>You only want to subclass list if your class could be used anywhere a list can be used. In fact this is a really good way to think about subclassing in general – subclasses should be specialized versions of the superclass. “Kind of” the same, but with a little different functionality.</p>
</section>
</section>
<section id="attribute-resolution-order">
<h3>Attribute Resolution Order<a class="headerlink" href="#attribute-resolution-order" title="Link to this heading"></a></h3>
<p>Once there is a potentially large hierarchy of subclasses, how do you know which one will be used?</p>
<p>When you access an attribute:</p>
<p><code class="docutils literal notranslate"><span class="pre">an_instance.something</span></code></p>
<p>Python looks for it in this order:</p>
<blockquote>
<div><ul class="simple">
<li><p>Is it an instance attribute ?</p></li>
<li><p>Is it a class attribute ?</p></li>
<li><p>Is it a superclass attribute ?</p></li>
<li><p>Is it a super-superclass attribute ?</p></li>
<li><p>…</p></li>
</ul>
</div></blockquote>
<p>It can get more complicated, particularly when there are multiple superclasses (multiple inheritance), but when there is a simple inheritance structure (the usual case) – it’s fairly straightforward.</p>
<p>This is often referred to as “method resolution order” (MRO), because it’s more complicated with methods, and in some languages, methods and attributes are more distinct than in Python. In Python, it can be thought of as “name resolution” – everything in Python is about names and namespaces.</p>
<p>If you want to know more of the gory details – here’s some reading:</p>
<p><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><a class="reference external" href="http://python-history.blogspot.com/2010/06/method-resolution-order.html">http://python-history.blogspot.com/2010/06/method-resolution-order.html</a></p>
</section>
<section id="what-are-python-classes-really">
<h3>What are Python classes, really?<a class="headerlink" href="#what-are-python-classes-really" title="Link to this heading"></a></h3>
<p>Putting aside the OO theory…</p>
<p>Python classes feature:</p>
<blockquote>
<div><ul class="simple">
<li><p>Namespaces</p>
<ul>
<li><p>One for the class object</p></li>
<li><p>One for each instance</p></li>
</ul>
</li>
<li><p>Attribute resolution order – how do you find an attribute.</p></li>
<li><p>Auto tacking-on of <code class="docutils literal notranslate"><span class="pre">self</span></code> when methods are called</p></li>
<li><p>automatically calling <code class="docutils literal notranslate"><span class="pre">__init__</span></code> when the class object is called.</p></li>
</ul>
</div></blockquote>
<p>That’s about it – really!</p>
<p>(Well, not really, there is more fancy stuff going on under the hood – but this basic structure will get you far).</p>
</section>
<section id="type-based-dispatch">
<h3>Type-Based Dispatch<a class="headerlink" href="#type-based-dispatch" title="Link to this heading"></a></h3>
<p>Occasionally you’ll see code that looks like this:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">A_Class</span><span class="p">):</span>
<span class="n">Do_something_with_other</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">Do_something_else</span>
</pre></div>
</div>
<p>When it’s called for, Python provides these utilities:</p>
<blockquote>
<div><ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">isinstance()</span></code></p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">issubclass()</span></code></p></li>
</ul>
</div></blockquote>
<p>But it is <em>very</em> rarely called for! Between Duck Typing, polymorphism, and EAFP, you rarely need to check for type directly.</p>
</section>
<section id="wrap-up">
<h3>Wrap Up<a class="headerlink" href="#wrap-up" title="Link to this heading"></a></h3>
<p>Thinking OO in Python:</p>
<p>Think about what makes sense for your code:</p>
<ul class="simple">
<li><p>Code re-use</p></li>
<li><p>Clean APIs</p></li>
<li><p>Separation of Concerns</p></li>
<li><p>…</p></li>
</ul>
<p>OO can be a very powerful approach, but don’t be a slave to what OO is <em>supposed</em> to look like.</p>
<p>Let OO work for you, not <em>create</em> work for you.</p>
<p>And the biggest way to do that is to support code re-use.</p>
</section>
</section>
</section>
</div>
</div>
<footer><div class="rst-footer-buttons" role="navigation" aria-label="Footer">
<a href="../topics/15-subclassing/index.html" class="btn btn-neutral float-left" title="15. Subclassing and Inheritance" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a>
<a href="../exercises/html_renderer/html_renderer.html" class="btn btn-neutral float-right" title="HTML Renderer Exercise" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right" aria-hidden="true"></span></a>
</div>
<hr/>
<div role="contentinfo">
<p>© Copyright 2025, Natasha Aleksandrova, Christopher Barker, Brian Dorsey, Cris Ewing, Christy Heaton, Jon Jacky, Maria McKinley, Andy Miles, Rick Riehle, Joseph Schilz, Joseph Sheedy, Hosung Song. Creative Commons Attribution-ShareAlike 4.0 license.</p>
</div>
Built with <a href="https://www.sphinx-doc.org/">Sphinx</a> using a
<a href="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script>
jQuery(function () {
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html>