classes.html 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
  6. <meta property="og:title" content="9. Classes" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/tutorial/classes.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have ..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have ..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>9. Classes &#8212; Python 3.12.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
  21. <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
  22. <script src="../_static/jquery.js"></script>
  23. <script src="../_static/underscore.js"></script>
  24. <script src="../_static/doctools.js"></script>
  25. <script src="../_static/sidebar.js"></script>
  26. <link rel="search" type="application/opensearchdescription+xml"
  27. title="Search within Python 3.12.0 documentation"
  28. href="../_static/opensearch.xml"/>
  29. <link rel="author" title="About these documents" href="../about.html" />
  30. <link rel="index" title="Index" href="../genindex.html" />
  31. <link rel="search" title="Search" href="../search.html" />
  32. <link rel="copyright" title="Copyright" href="../copyright.html" />
  33. <link rel="next" title="10. Brief Tour of the Standard Library" href="stdlib.html" />
  34. <link rel="prev" title="8. Errors and Exceptions" href="errors.html" />
  35. <link rel="canonical" href="https://docs.python.org/3/tutorial/classes.html" />
  36. <style>
  37. @media only screen {
  38. table.full-width-table {
  39. width: 100%;
  40. }
  41. }
  42. </style>
  43. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  44. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  45. <script type="text/javascript" src="../_static/copybutton.js"></script>
  46. <script type="text/javascript" src="../_static/menu.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" 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"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">9. Classes</a><ul>
  86. <li><a class="reference internal" href="#a-word-about-names-and-objects">9.1. A Word About Names and Objects</a></li>
  87. <li><a class="reference internal" href="#python-scopes-and-namespaces">9.2. Python Scopes and Namespaces</a><ul>
  88. <li><a class="reference internal" href="#scopes-and-namespaces-example">9.2.1. Scopes and Namespaces Example</a></li>
  89. </ul>
  90. </li>
  91. <li><a class="reference internal" href="#a-first-look-at-classes">9.3. A First Look at Classes</a><ul>
  92. <li><a class="reference internal" href="#class-definition-syntax">9.3.1. Class Definition Syntax</a></li>
  93. <li><a class="reference internal" href="#class-objects">9.3.2. Class Objects</a></li>
  94. <li><a class="reference internal" href="#instance-objects">9.3.3. Instance Objects</a></li>
  95. <li><a class="reference internal" href="#method-objects">9.3.4. Method Objects</a></li>
  96. <li><a class="reference internal" href="#class-and-instance-variables">9.3.5. Class and Instance Variables</a></li>
  97. </ul>
  98. </li>
  99. <li><a class="reference internal" href="#random-remarks">9.4. Random Remarks</a></li>
  100. <li><a class="reference internal" href="#inheritance">9.5. Inheritance</a><ul>
  101. <li><a class="reference internal" href="#multiple-inheritance">9.5.1. Multiple Inheritance</a></li>
  102. </ul>
  103. </li>
  104. <li><a class="reference internal" href="#private-variables">9.6. Private Variables</a></li>
  105. <li><a class="reference internal" href="#odds-and-ends">9.7. Odds and Ends</a></li>
  106. <li><a class="reference internal" href="#iterators">9.8. Iterators</a></li>
  107. <li><a class="reference internal" href="#generators">9.9. Generators</a></li>
  108. <li><a class="reference internal" href="#generator-expressions">9.10. Generator Expressions</a></li>
  109. </ul>
  110. </li>
  111. </ul>
  112. </div>
  113. <div>
  114. <h4>Previous topic</h4>
  115. <p class="topless"><a href="errors.html"
  116. title="previous chapter"><span class="section-number">8. </span>Errors and Exceptions</a></p>
  117. </div>
  118. <div>
  119. <h4>Next topic</h4>
  120. <p class="topless"><a href="stdlib.html"
  121. title="next chapter"><span class="section-number">10. </span>Brief Tour of the Standard Library</a></p>
  122. </div>
  123. <div role="note" aria-label="source link">
  124. <h3>This Page</h3>
  125. <ul class="this-page-menu">
  126. <li><a href="../bugs.html">Report a Bug</a></li>
  127. <li>
  128. <a href="https://github.com/python/cpython/blob/main/Doc/tutorial/classes.rst"
  129. rel="nofollow">Show Source
  130. </a>
  131. </li>
  132. </ul>
  133. </div>
  134. </nav>
  135. </div>
  136. </div>
  137. <div class="related" role="navigation" aria-label="related navigation">
  138. <h3>Navigation</h3>
  139. <ul>
  140. <li class="right" style="margin-right: 10px">
  141. <a href="../genindex.html" title="General Index"
  142. accesskey="I">index</a></li>
  143. <li class="right" >
  144. <a href="../py-modindex.html" title="Python Module Index"
  145. >modules</a> |</li>
  146. <li class="right" >
  147. <a href="stdlib.html" title="10. Brief Tour of the Standard Library"
  148. accesskey="N">next</a> |</li>
  149. <li class="right" >
  150. <a href="errors.html" title="8. Errors and Exceptions"
  151. accesskey="P">previous</a> |</li>
  152. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  153. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  154. <li class="switchers">
  155. <div class="language_switcher_placeholder"></div>
  156. <div class="version_switcher_placeholder"></div>
  157. </li>
  158. <li>
  159. </li>
  160. <li id="cpython-language-and-version">
  161. <a href="../index.html">3.12.0 Documentation</a> &#187;
  162. </li>
  163. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
  164. <li class="nav-item nav-item-this"><a href=""><span class="section-number">9. </span>Classes</a></li>
  165. <li class="right">
  166. <div class="inline-search" role="search">
  167. <form class="inline-search" action="../search.html" method="get">
  168. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  169. <input type="submit" value="Go" />
  170. </form>
  171. </div>
  172. |
  173. </li>
  174. <li class="right">
  175. <label class="theme-selector-label">
  176. Theme
  177. <select class="theme-selector" oninput="activateTheme(this.value)">
  178. <option value="auto" selected>Auto</option>
  179. <option value="light">Light</option>
  180. <option value="dark">Dark</option>
  181. </select>
  182. </label> |</li>
  183. </ul>
  184. </div>
  185. <div class="document">
  186. <div class="documentwrapper">
  187. <div class="bodywrapper">
  188. <div class="body" role="main">
  189. <section id="classes">
  190. <span id="tut-classes"></span><h1><span class="section-number">9. </span>Classes<a class="headerlink" href="#classes" title="Permalink to this headline">¶</a></h1>
  191. <p>Classes provide a means of bundling data and functionality together. Creating
  192. a new class creates a new <em>type</em> of object, allowing new <em>instances</em> of that
  193. type to be made. Each class instance can have attributes attached to it for
  194. maintaining its state. Class instances can also have methods (defined by its
  195. class) for modifying its state.</p>
  196. <p>Compared with other programming languages, Python’s class mechanism adds classes
  197. with a minimum of new syntax and semantics. It is a mixture of the class
  198. mechanisms found in C++ and Modula-3. Python classes provide all the standard
  199. features of Object Oriented Programming: the class inheritance mechanism allows
  200. multiple base classes, a derived class can override any methods of its base
  201. class or classes, and a method can call the method of a base class with the same
  202. name. Objects can contain arbitrary amounts and kinds of data. As is true for
  203. modules, classes partake of the dynamic nature of Python: they are created at
  204. runtime, and can be modified further after creation.</p>
  205. <p>In C++ terminology, normally class members (including the data members) are
  206. <em>public</em> (except see below <a class="reference internal" href="#tut-private"><span class="std std-ref">Private Variables</span></a>), and all member functions are
  207. <em>virtual</em>. As in Modula-3, there are no shorthands for referencing the object’s
  208. members from its methods: the method function is declared with an explicit first
  209. argument representing the object, which is provided implicitly by the call. As
  210. in Smalltalk, classes themselves are objects. This provides semantics for
  211. importing and renaming. Unlike C++ and Modula-3, built-in types can be used as
  212. base classes for extension by the user. Also, like in C++, most built-in
  213. operators with special syntax (arithmetic operators, subscripting etc.) can be
  214. redefined for class instances.</p>
  215. <p>(Lacking universally accepted terminology to talk about classes, I will make
  216. occasional use of Smalltalk and C++ terms. I would use Modula-3 terms, since
  217. its object-oriented semantics are closer to those of Python than C++, but I
  218. expect that few readers have heard of it.)</p>
  219. <section id="a-word-about-names-and-objects">
  220. <span id="tut-object"></span><h2><span class="section-number">9.1. </span>A Word About Names and Objects<a class="headerlink" href="#a-word-about-names-and-objects" title="Permalink to this headline">¶</a></h2>
  221. <p>Objects have individuality, and multiple names (in multiple scopes) can be bound
  222. to the same object. This is known as aliasing in other languages. This is
  223. usually not appreciated on a first glance at Python, and can be safely ignored
  224. when dealing with immutable basic types (numbers, strings, tuples). However,
  225. aliasing has a possibly surprising effect on the semantics of Python code
  226. involving mutable objects such as lists, dictionaries, and most other types.
  227. This is usually used to the benefit of the program, since aliases behave like
  228. pointers in some respects. For example, passing an object is cheap since only a
  229. pointer is passed by the implementation; and if a function modifies an object
  230. passed as an argument, the caller will see the change — this eliminates the
  231. need for two different argument passing mechanisms as in Pascal.</p>
  232. </section>
  233. <section id="python-scopes-and-namespaces">
  234. <span id="tut-scopes"></span><h2><span class="section-number">9.2. </span>Python Scopes and Namespaces<a class="headerlink" href="#python-scopes-and-namespaces" title="Permalink to this headline">¶</a></h2>
  235. <p>Before introducing classes, I first have to tell you something about Python’s
  236. scope rules. Class definitions play some neat tricks with namespaces, and you
  237. need to know how scopes and namespaces work to fully understand what’s going on.
  238. Incidentally, knowledge about this subject is useful for any advanced Python
  239. programmer.</p>
  240. <p>Let’s begin with some definitions.</p>
  241. <p>A <em>namespace</em> is a mapping from names to objects. Most namespaces are currently
  242. implemented as Python dictionaries, but that’s normally not noticeable in any
  243. way (except for performance), and it may change in the future. Examples of
  244. namespaces are: the set of built-in names (containing functions such as <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>, and
  245. built-in exception names); the global names in a module; and the local names in
  246. a function invocation. In a sense the set of attributes of an object also form
  247. a namespace. The important thing to know about namespaces is that there is
  248. absolutely no relation between names in different namespaces; for instance, two
  249. different modules may both define a function <code class="docutils literal notranslate"><span class="pre">maximize</span></code> without confusion —
  250. users of the modules must prefix it with the module name.</p>
  251. <p>By the way, I use the word <em>attribute</em> for any name following a dot — for
  252. example, in the expression <code class="docutils literal notranslate"><span class="pre">z.real</span></code>, <code class="docutils literal notranslate"><span class="pre">real</span></code> is an attribute of the object
  253. <code class="docutils literal notranslate"><span class="pre">z</span></code>. Strictly speaking, references to names in modules are attribute
  254. references: in the expression <code class="docutils literal notranslate"><span class="pre">modname.funcname</span></code>, <code class="docutils literal notranslate"><span class="pre">modname</span></code> is a module
  255. object and <code class="docutils literal notranslate"><span class="pre">funcname</span></code> is an attribute of it. In this case there happens to be
  256. a straightforward mapping between the module’s attributes and the global names
  257. defined in the module: they share the same namespace! <a class="footnote-reference brackets" href="#id2" id="id1">1</a></p>
  258. <p>Attributes may be read-only or writable. In the latter case, assignment to
  259. attributes is possible. Module attributes are writable: you can write
  260. <code class="docutils literal notranslate"><span class="pre">modname.the_answer</span> <span class="pre">=</span> <span class="pre">42</span></code>. Writable attributes may also be deleted with the
  261. <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement. For example, <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">modname.the_answer</span></code> will remove
  262. the attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">the_answer</span></code> from the object named by <code class="docutils literal notranslate"><span class="pre">modname</span></code>.</p>
  263. <p>Namespaces are created at different moments and have different lifetimes. The
  264. namespace containing the built-in names is created when the Python interpreter
  265. starts up, and is never deleted. The global namespace for a module is created
  266. when the module definition is read in; normally, module namespaces also last
  267. until the interpreter quits. The statements executed by the top-level
  268. invocation of the interpreter, either read from a script file or interactively,
  269. are considered part of a module called <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>, so they have their own
  270. global namespace. (The built-in names actually also live in a module; this is
  271. called <a class="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a>.)</p>
  272. <p>The local namespace for a function is created when the function is called, and
  273. deleted when the function returns or raises an exception that is not handled
  274. within the function. (Actually, forgetting would be a better way to describe
  275. what actually happens.) Of course, recursive invocations each have their own
  276. local namespace.</p>
  277. <p>A <em>scope</em> is a textual region of a Python program where a namespace is directly
  278. accessible. “Directly accessible” here means that an unqualified reference to a
  279. name attempts to find the name in the namespace.</p>
  280. <p>Although scopes are determined statically, they are used dynamically. At any
  281. time during execution, there are 3 or 4 nested scopes whose namespaces are
  282. directly accessible:</p>
  283. <ul class="simple">
  284. <li><p>the innermost scope, which is searched first, contains the local names</p></li>
  285. <li><p>the scopes of any enclosing functions, which are searched starting with the
  286. nearest enclosing scope, contain non-local, but also non-global names</p></li>
  287. <li><p>the next-to-last scope contains the current module’s global names</p></li>
  288. <li><p>the outermost scope (searched last) is the namespace containing built-in names</p></li>
  289. </ul>
  290. <p>If a name is declared global, then all references and assignments go directly to
  291. the next-to-last scope containing the module’s global names. To rebind variables
  292. found outside of the innermost scope, the <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> statement can be
  293. used; if not declared nonlocal, those variables are read-only (an attempt to
  294. write to such a variable will simply create a <em>new</em> local variable in the
  295. innermost scope, leaving the identically named outer variable unchanged).</p>
  296. <p>Usually, the local scope references the local names of the (textually) current
  297. function. Outside functions, the local scope references the same namespace as
  298. the global scope: the module’s namespace. Class definitions place yet another
  299. namespace in the local scope.</p>
  300. <p>It is important to realize that scopes are determined textually: the global
  301. scope of a function defined in a module is that module’s namespace, no matter
  302. from where or by what alias the function is called. On the other hand, the
  303. actual search for names is done dynamically, at run time — however, the
  304. language definition is evolving towards static name resolution, at “compile”
  305. time, so don’t rely on dynamic name resolution! (In fact, local variables are
  306. already determined statically.)</p>
  307. <p>A special quirk of Python is that – if no <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> or <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a>
  308. statement is in effect – assignments to names always go into the innermost scope.
  309. Assignments do not copy data — they just bind names to objects. The same is true
  310. for deletions: the statement <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">x</span></code> removes the binding of <code class="docutils literal notranslate"><span class="pre">x</span></code> from the
  311. namespace referenced by the local scope. In fact, all operations that introduce
  312. new names use the local scope: in particular, <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements and
  313. function definitions bind the module or function name in the local scope.</p>
  314. <p>The <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement can be used to indicate that particular
  315. variables live in the global scope and should be rebound there; the
  316. <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> statement indicates that particular variables live in
  317. an enclosing scope and should be rebound there.</p>
  318. <section id="scopes-and-namespaces-example">
  319. <span id="tut-scopeexample"></span><h3><span class="section-number">9.2.1. </span>Scopes and Namespaces Example<a class="headerlink" href="#scopes-and-namespaces-example" title="Permalink to this headline">¶</a></h3>
  320. <p>This is an example demonstrating how to reference the different scopes and
  321. namespaces, and how <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> and <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> affect variable
  322. binding:</p>
  323. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">scope_test</span><span class="p">():</span>
  324. <span class="k">def</span> <span class="nf">do_local</span><span class="p">():</span>
  325. <span class="n">spam</span> <span class="o">=</span> <span class="s2">&quot;local spam&quot;</span>
  326. <span class="k">def</span> <span class="nf">do_nonlocal</span><span class="p">():</span>
  327. <span class="k">nonlocal</span> <span class="n">spam</span>
  328. <span class="n">spam</span> <span class="o">=</span> <span class="s2">&quot;nonlocal spam&quot;</span>
  329. <span class="k">def</span> <span class="nf">do_global</span><span class="p">():</span>
  330. <span class="k">global</span> <span class="n">spam</span>
  331. <span class="n">spam</span> <span class="o">=</span> <span class="s2">&quot;global spam&quot;</span>
  332. <span class="n">spam</span> <span class="o">=</span> <span class="s2">&quot;test spam&quot;</span>
  333. <span class="n">do_local</span><span class="p">()</span>
  334. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;After local assignment:&quot;</span><span class="p">,</span> <span class="n">spam</span><span class="p">)</span>
  335. <span class="n">do_nonlocal</span><span class="p">()</span>
  336. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;After nonlocal assignment:&quot;</span><span class="p">,</span> <span class="n">spam</span><span class="p">)</span>
  337. <span class="n">do_global</span><span class="p">()</span>
  338. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;After global assignment:&quot;</span><span class="p">,</span> <span class="n">spam</span><span class="p">)</span>
  339. <span class="n">scope_test</span><span class="p">()</span>
  340. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;In global scope:&quot;</span><span class="p">,</span> <span class="n">spam</span><span class="p">)</span>
  341. </pre></div>
  342. </div>
  343. <p>The output of the example code is:</p>
  344. <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>After local assignment: test spam
  345. After nonlocal assignment: nonlocal spam
  346. After global assignment: nonlocal spam
  347. In global scope: global spam
  348. </pre></div>
  349. </div>
  350. <p>Note how the <em>local</em> assignment (which is default) didn’t change <em>scope_test</em>'s
  351. binding of <em>spam</em>. The <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> assignment changed <em>scope_test</em>'s
  352. binding of <em>spam</em>, and the <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> assignment changed the module-level
  353. binding.</p>
  354. <p>You can also see that there was no previous binding for <em>spam</em> before the
  355. <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> assignment.</p>
  356. </section>
  357. </section>
  358. <section id="a-first-look-at-classes">
  359. <span id="tut-firstclasses"></span><h2><span class="section-number">9.3. </span>A First Look at Classes<a class="headerlink" href="#a-first-look-at-classes" title="Permalink to this headline">¶</a></h2>
  360. <p>Classes introduce a little bit of new syntax, three new object types, and some
  361. new semantics.</p>
  362. <section id="class-definition-syntax">
  363. <span id="tut-classdefinition"></span><h3><span class="section-number">9.3.1. </span>Class Definition Syntax<a class="headerlink" href="#class-definition-syntax" title="Permalink to this headline">¶</a></h3>
  364. <p>The simplest form of class definition looks like this:</p>
  365. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ClassName</span><span class="p">:</span>
  366. <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="mi">1</span><span class="o">&gt;</span>
  367. <span class="o">.</span>
  368. <span class="o">.</span>
  369. <span class="o">.</span>
  370. <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="n">N</span><span class="o">&gt;</span>
  371. </pre></div>
  372. </div>
  373. <p>Class definitions, like function definitions (<a class="reference internal" href="../reference/compound_stmts.html#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a> statements) must be
  374. executed before they have any effect. (You could conceivably place a class
  375. definition in a branch of an <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement, or inside a function.)</p>
  376. <p>In practice, the statements inside a class definition will usually be function
  377. definitions, but other statements are allowed, and sometimes useful — we’ll
  378. come back to this later. The function definitions inside a class normally have
  379. a peculiar form of argument list, dictated by the calling conventions for
  380. methods — again, this is explained later.</p>
  381. <p>When a class definition is entered, a new namespace is created, and used as the
  382. local scope — thus, all assignments to local variables go into this new
  383. namespace. In particular, function definitions bind the name of the new
  384. function here.</p>
  385. <p>When a class definition is left normally (via the end), a <em>class object</em> is
  386. created. This is basically a wrapper around the contents of the namespace
  387. created by the class definition; we’ll learn more about class objects in the
  388. next section. The original local scope (the one in effect just before the class
  389. definition was entered) is reinstated, and the class object is bound here to the
  390. class name given in the class definition header (<code class="xref py py-class docutils literal notranslate"><span class="pre">ClassName</span></code> in the
  391. example).</p>
  392. </section>
  393. <section id="class-objects">
  394. <span id="tut-classobjects"></span><h3><span class="section-number">9.3.2. </span>Class Objects<a class="headerlink" href="#class-objects" title="Permalink to this headline">¶</a></h3>
  395. <p>Class objects support two kinds of operations: attribute references and
  396. instantiation.</p>
  397. <p><em>Attribute references</em> use the standard syntax used for all attribute references
  398. in Python: <code class="docutils literal notranslate"><span class="pre">obj.name</span></code>. Valid attribute names are all the names that were in
  399. the class’s namespace when the class object was created. So, if the class
  400. definition looked like this:</p>
  401. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyClass</span><span class="p">:</span>
  402. <span class="w"> </span><span class="sd">&quot;&quot;&quot;A simple example class&quot;&quot;&quot;</span>
  403. <span class="n">i</span> <span class="o">=</span> <span class="mi">12345</span>
  404. <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  405. <span class="k">return</span> <span class="s1">&#39;hello world&#39;</span>
  406. </pre></div>
  407. </div>
  408. <p>then <code class="docutils literal notranslate"><span class="pre">MyClass.i</span></code> and <code class="docutils literal notranslate"><span class="pre">MyClass.f</span></code> are valid attribute references, returning
  409. an integer and a function object, respectively. Class attributes can also be
  410. assigned to, so you can change the value of <code class="docutils literal notranslate"><span class="pre">MyClass.i</span></code> by assignment.
  411. <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is also a valid attribute, returning the docstring belonging to
  412. the class: <code class="docutils literal notranslate"><span class="pre">&quot;A</span> <span class="pre">simple</span> <span class="pre">example</span> <span class="pre">class&quot;</span></code>.</p>
  413. <p>Class <em>instantiation</em> uses function notation. Just pretend that the class
  414. object is a parameterless function that returns a new instance of the class.
  415. For example (assuming the above class):</p>
  416. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">MyClass</span><span class="p">()</span>
  417. </pre></div>
  418. </div>
  419. <p>creates a new <em>instance</em> of the class and assigns this object to the local
  420. variable <code class="docutils literal notranslate"><span class="pre">x</span></code>.</p>
  421. <p>The instantiation operation (“calling” a class object) creates an empty object.
  422. Many classes like to create objects with instances customized to a specific
  423. initial state. Therefore a class may define a special method named
  424. <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>, like this:</p>
  425. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  426. <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="p">[]</span>
  427. </pre></div>
  428. </div>
  429. <p>When a class defines an <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method, class instantiation
  430. automatically invokes <code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code> for the newly created class instance. So
  431. in this example, a new, initialized instance can be obtained by:</p>
  432. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">MyClass</span><span class="p">()</span>
  433. </pre></div>
  434. </div>
  435. <p>Of course, the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method may have arguments for greater
  436. flexibility. In that case, arguments given to the class instantiation operator
  437. are passed on to <code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code>. For example,</p>
  438. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Complex</span><span class="p">:</span>
  439. <span class="gp">... </span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">realpart</span><span class="p">,</span> <span class="n">imagpart</span><span class="p">):</span>
  440. <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">r</span> <span class="o">=</span> <span class="n">realpart</span>
  441. <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">i</span> <span class="o">=</span> <span class="n">imagpart</span>
  442. <span class="gp">...</span>
  443. <span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="n">Complex</span><span class="p">(</span><span class="mf">3.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">4.5</span><span class="p">)</span>
  444. <span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">r</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">i</span>
  445. <span class="go">(3.0, -4.5)</span>
  446. </pre></div>
  447. </div>
  448. </section>
  449. <section id="instance-objects">
  450. <span id="tut-instanceobjects"></span><h3><span class="section-number">9.3.3. </span>Instance Objects<a class="headerlink" href="#instance-objects" title="Permalink to this headline">¶</a></h3>
  451. <p>Now what can we do with instance objects? The only operations understood by
  452. instance objects are attribute references. There are two kinds of valid
  453. attribute names: data attributes and methods.</p>
  454. <p><em>data attributes</em> correspond to “instance variables” in Smalltalk, and to “data
  455. members” in C++. Data attributes need not be declared; like local variables,
  456. they spring into existence when they are first assigned to. For example, if
  457. <code class="docutils literal notranslate"><span class="pre">x</span></code> is the instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">MyClass</span></code> created above, the following piece of
  458. code will print the value <code class="docutils literal notranslate"><span class="pre">16</span></code>, without leaving a trace:</p>
  459. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">=</span> <span class="mi">1</span>
  460. <span class="k">while</span> <span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">:</span>
  461. <span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">*</span> <span class="mi">2</span>
  462. <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="o">.</span><span class="n">counter</span><span class="p">)</span>
  463. <span class="k">del</span> <span class="n">x</span><span class="o">.</span><span class="n">counter</span>
  464. </pre></div>
  465. </div>
  466. <p>The other kind of instance attribute reference is a <em>method</em>. A method is a
  467. function that “belongs to” an object. (In Python, the term method is not unique
  468. to class instances: other object types can have methods as well. For example,
  469. list objects have methods called append, insert, remove, sort, and so on.
  470. However, in the following discussion, we’ll use the term method exclusively to
  471. mean methods of class instance objects, unless explicitly stated otherwise.)</p>
  472. <p id="index-0">Valid method names of an instance object depend on its class. By definition,
  473. all attributes of a class that are function objects define corresponding
  474. methods of its instances. So in our example, <code class="docutils literal notranslate"><span class="pre">x.f</span></code> is a valid method
  475. reference, since <code class="docutils literal notranslate"><span class="pre">MyClass.f</span></code> is a function, but <code class="docutils literal notranslate"><span class="pre">x.i</span></code> is not, since
  476. <code class="docutils literal notranslate"><span class="pre">MyClass.i</span></code> is not. But <code class="docutils literal notranslate"><span class="pre">x.f</span></code> is not the same thing as <code class="docutils literal notranslate"><span class="pre">MyClass.f</span></code> — it
  477. is a <em>method object</em>, not a function object.</p>
  478. </section>
  479. <section id="method-objects">
  480. <span id="tut-methodobjects"></span><h3><span class="section-number">9.3.4. </span>Method Objects<a class="headerlink" href="#method-objects" title="Permalink to this headline">¶</a></h3>
  481. <p>Usually, a method is called right after it is bound:</p>
  482. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span><span class="o">.</span><span class="n">f</span><span class="p">()</span>
  483. </pre></div>
  484. </div>
  485. <p>In the <code class="xref py py-class docutils literal notranslate"><span class="pre">MyClass</span></code> example, this will return the string <code class="docutils literal notranslate"><span class="pre">'hello</span> <span class="pre">world'</span></code>.
  486. However, it is not necessary to call a method right away: <code class="docutils literal notranslate"><span class="pre">x.f</span></code> is a method
  487. object, and can be stored away and called at a later time. For example:</p>
  488. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">xf</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">f</span>
  489. <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
  490. <span class="nb">print</span><span class="p">(</span><span class="n">xf</span><span class="p">())</span>
  491. </pre></div>
  492. </div>
  493. <p>will continue to print <code class="docutils literal notranslate"><span class="pre">hello</span> <span class="pre">world</span></code> until the end of time.</p>
  494. <p>What exactly happens when a method is called? You may have noticed that
  495. <code class="docutils literal notranslate"><span class="pre">x.f()</span></code> was called without an argument above, even though the function
  496. definition for <code class="xref py py-meth docutils literal notranslate"><span class="pre">f()</span></code> specified an argument. What happened to the argument?
  497. Surely Python raises an exception when a function that requires an argument is
  498. called without any — even if the argument isn’t actually used…</p>
  499. <p>Actually, you may have guessed the answer: the special thing about methods is
  500. that the instance object is passed as the first argument of the function. In our
  501. example, the call <code class="docutils literal notranslate"><span class="pre">x.f()</span></code> is exactly equivalent to <code class="docutils literal notranslate"><span class="pre">MyClass.f(x)</span></code>. In
  502. general, calling a method with a list of <em>n</em> arguments is equivalent to calling
  503. the corresponding function with an argument list that is created by inserting
  504. the method’s instance object before the first argument.</p>
  505. <p>If you still don’t understand how methods work, a look at the implementation can
  506. perhaps clarify matters. When a non-data attribute of an instance is
  507. referenced, the instance’s class is searched. If the name denotes a valid class
  508. attribute that is a function object, a method object is created by packing
  509. (pointers to) the instance object and the function object just found together in
  510. an abstract object: this is the method object. When the method object is called
  511. with an argument list, a new argument list is constructed from the instance
  512. object and the argument list, and the function object is called with this new
  513. argument list.</p>
  514. </section>
  515. <section id="class-and-instance-variables">
  516. <span id="tut-class-and-instance-variables"></span><h3><span class="section-number">9.3.5. </span>Class and Instance Variables<a class="headerlink" href="#class-and-instance-variables" title="Permalink to this headline">¶</a></h3>
  517. <p>Generally speaking, instance variables are for data unique to each instance
  518. and class variables are for attributes and methods shared by all instances
  519. of the class:</p>
  520. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Dog</span><span class="p">:</span>
  521. <span class="n">kind</span> <span class="o">=</span> <span class="s1">&#39;canine&#39;</span> <span class="c1"># class variable shared by all instances</span>
  522. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
  523. <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span> <span class="c1"># instance variable unique to each instance</span>
  524. <span class="o">&gt;&gt;&gt;</span> <span class="n">d</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Fido&#39;</span><span class="p">)</span>
  525. <span class="o">&gt;&gt;&gt;</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Buddy&#39;</span><span class="p">)</span>
  526. <span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">kind</span> <span class="c1"># shared by all dogs</span>
  527. <span class="s1">&#39;canine&#39;</span>
  528. <span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">kind</span> <span class="c1"># shared by all dogs</span>
  529. <span class="s1">&#39;canine&#39;</span>
  530. <span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">name</span> <span class="c1"># unique to d</span>
  531. <span class="s1">&#39;Fido&#39;</span>
  532. <span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">name</span> <span class="c1"># unique to e</span>
  533. <span class="s1">&#39;Buddy&#39;</span>
  534. </pre></div>
  535. </div>
  536. <p>As discussed in <a class="reference internal" href="#tut-object"><span class="std std-ref">A Word About Names and Objects</span></a>, shared data can have possibly surprising
  537. effects with involving <a class="reference internal" href="../glossary.html#term-mutable"><span class="xref std std-term">mutable</span></a> objects such as lists and dictionaries.
  538. For example, the <em>tricks</em> list in the following code should not be used as a
  539. class variable because just a single list would be shared by all <em>Dog</em>
  540. instances:</p>
  541. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Dog</span><span class="p">:</span>
  542. <span class="n">tricks</span> <span class="o">=</span> <span class="p">[]</span> <span class="c1"># mistaken use of a class variable</span>
  543. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
  544. <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
  545. <span class="k">def</span> <span class="nf">add_trick</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">trick</span><span class="p">):</span>
  546. <span class="bp">self</span><span class="o">.</span><span class="n">tricks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">trick</span><span class="p">)</span>
  547. <span class="o">&gt;&gt;&gt;</span> <span class="n">d</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Fido&#39;</span><span class="p">)</span>
  548. <span class="o">&gt;&gt;&gt;</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Buddy&#39;</span><span class="p">)</span>
  549. <span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;roll over&#39;</span><span class="p">)</span>
  550. <span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;play dead&#39;</span><span class="p">)</span>
  551. <span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">tricks</span> <span class="c1"># unexpectedly shared by all dogs</span>
  552. <span class="p">[</span><span class="s1">&#39;roll over&#39;</span><span class="p">,</span> <span class="s1">&#39;play dead&#39;</span><span class="p">]</span>
  553. </pre></div>
  554. </div>
  555. <p>Correct design of the class should use an instance variable instead:</p>
  556. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Dog</span><span class="p">:</span>
  557. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
  558. <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
  559. <span class="bp">self</span><span class="o">.</span><span class="n">tricks</span> <span class="o">=</span> <span class="p">[]</span> <span class="c1"># creates a new empty list for each dog</span>
  560. <span class="k">def</span> <span class="nf">add_trick</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">trick</span><span class="p">):</span>
  561. <span class="bp">self</span><span class="o">.</span><span class="n">tricks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">trick</span><span class="p">)</span>
  562. <span class="o">&gt;&gt;&gt;</span> <span class="n">d</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Fido&#39;</span><span class="p">)</span>
  563. <span class="o">&gt;&gt;&gt;</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Buddy&#39;</span><span class="p">)</span>
  564. <span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;roll over&#39;</span><span class="p">)</span>
  565. <span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;play dead&#39;</span><span class="p">)</span>
  566. <span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">tricks</span>
  567. <span class="p">[</span><span class="s1">&#39;roll over&#39;</span><span class="p">]</span>
  568. <span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">tricks</span>
  569. <span class="p">[</span><span class="s1">&#39;play dead&#39;</span><span class="p">]</span>
  570. </pre></div>
  571. </div>
  572. </section>
  573. </section>
  574. <section id="random-remarks">
  575. <span id="tut-remarks"></span><h2><span class="section-number">9.4. </span>Random Remarks<a class="headerlink" href="#random-remarks" title="Permalink to this headline">¶</a></h2>
  576. <p>If the same attribute name occurs in both an instance and in a class,
  577. then attribute lookup prioritizes the instance:</p>
  578. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Warehouse</span><span class="p">:</span>
  579. <span class="gp">... </span> <span class="n">purpose</span> <span class="o">=</span> <span class="s1">&#39;storage&#39;</span>
  580. <span class="gp">... </span> <span class="n">region</span> <span class="o">=</span> <span class="s1">&#39;west&#39;</span>
  581. <span class="gp">...</span>
  582. <span class="gp">&gt;&gt;&gt; </span><span class="n">w1</span> <span class="o">=</span> <span class="n">Warehouse</span><span class="p">()</span>
  583. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">w1</span><span class="o">.</span><span class="n">purpose</span><span class="p">,</span> <span class="n">w1</span><span class="o">.</span><span class="n">region</span><span class="p">)</span>
  584. <span class="go">storage west</span>
  585. <span class="gp">&gt;&gt;&gt; </span><span class="n">w2</span> <span class="o">=</span> <span class="n">Warehouse</span><span class="p">()</span>
  586. <span class="gp">&gt;&gt;&gt; </span><span class="n">w2</span><span class="o">.</span><span class="n">region</span> <span class="o">=</span> <span class="s1">&#39;east&#39;</span>
  587. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">w2</span><span class="o">.</span><span class="n">purpose</span><span class="p">,</span> <span class="n">w2</span><span class="o">.</span><span class="n">region</span><span class="p">)</span>
  588. <span class="go">storage east</span>
  589. </pre></div>
  590. </div>
  591. <p>Data attributes may be referenced by methods as well as by ordinary users
  592. (“clients”) of an object. In other words, classes are not usable to implement
  593. pure abstract data types. In fact, nothing in Python makes it possible to
  594. enforce data hiding — it is all based upon convention. (On the other hand,
  595. the Python implementation, written in C, can completely hide implementation
  596. details and control access to an object if necessary; this can be used by
  597. extensions to Python written in C.)</p>
  598. <p>Clients should use data attributes with care — clients may mess up invariants
  599. maintained by the methods by stamping on their data attributes. Note that
  600. clients may add data attributes of their own to an instance object without
  601. affecting the validity of the methods, as long as name conflicts are avoided —
  602. again, a naming convention can save a lot of headaches here.</p>
  603. <p>There is no shorthand for referencing data attributes (or other methods!) from
  604. within methods. I find that this actually increases the readability of methods:
  605. there is no chance of confusing local variables and instance variables when
  606. glancing through a method.</p>
  607. <p>Often, the first argument of a method is called <code class="docutils literal notranslate"><span class="pre">self</span></code>. This is nothing more
  608. than a convention: the name <code class="docutils literal notranslate"><span class="pre">self</span></code> has absolutely no special meaning to
  609. Python. Note, however, that by not following the convention your code may be
  610. less readable to other Python programmers, and it is also conceivable that a
  611. <em>class browser</em> program might be written that relies upon such a convention.</p>
  612. <p>Any function object that is a class attribute defines a method for instances of
  613. that class. It is not necessary that the function definition is textually
  614. enclosed in the class definition: assigning a function object to a local
  615. variable in the class is also ok. For example:</p>
  616. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Function defined outside the class</span>
  617. <span class="k">def</span> <span class="nf">f1</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
  618. <span class="k">return</span> <span class="nb">min</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">)</span>
  619. <span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
  620. <span class="n">f</span> <span class="o">=</span> <span class="n">f1</span>
  621. <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  622. <span class="k">return</span> <span class="s1">&#39;hello world&#39;</span>
  623. <span class="n">h</span> <span class="o">=</span> <span class="n">g</span>
  624. </pre></div>
  625. </div>
  626. <p>Now <code class="docutils literal notranslate"><span class="pre">f</span></code>, <code class="docutils literal notranslate"><span class="pre">g</span></code> and <code class="docutils literal notranslate"><span class="pre">h</span></code> are all attributes of class <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> that refer to
  627. function objects, and consequently they are all methods of instances of
  628. <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> — <code class="docutils literal notranslate"><span class="pre">h</span></code> being exactly equivalent to <code class="docutils literal notranslate"><span class="pre">g</span></code>. Note that this practice
  629. usually only serves to confuse the reader of a program.</p>
  630. <p>Methods may call other methods by using method attributes of the <code class="docutils literal notranslate"><span class="pre">self</span></code>
  631. argument:</p>
  632. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Bag</span><span class="p">:</span>
  633. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  634. <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="p">[]</span>
  635. <span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
  636. <span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  637. <span class="k">def</span> <span class="nf">addtwice</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
  638. <span class="bp">self</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  639. <span class="bp">self</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  640. </pre></div>
  641. </div>
  642. <p>Methods may reference global names in the same way as ordinary functions. The
  643. global scope associated with a method is the module containing its
  644. definition. (A class is never used as a global scope.) While one
  645. rarely encounters a good reason for using global data in a method, there are
  646. many legitimate uses of the global scope: for one thing, functions and modules
  647. imported into the global scope can be used by methods, as well as functions and
  648. classes defined in it. Usually, the class containing the method is itself
  649. defined in this global scope, and in the next section we’ll find some good
  650. reasons why a method would want to reference its own class.</p>
  651. <p>Each value is an object, and therefore has a <em>class</em> (also called its <em>type</em>).
  652. It is stored as <code class="docutils literal notranslate"><span class="pre">object.__class__</span></code>.</p>
  653. </section>
  654. <section id="inheritance">
  655. <span id="tut-inheritance"></span><h2><span class="section-number">9.5. </span>Inheritance<a class="headerlink" href="#inheritance" title="Permalink to this headline">¶</a></h2>
  656. <p>Of course, a language feature would not be worthy of the name “class” without
  657. supporting inheritance. The syntax for a derived class definition looks like
  658. this:</p>
  659. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DerivedClassName</span><span class="p">(</span><span class="n">BaseClassName</span><span class="p">):</span>
  660. <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="mi">1</span><span class="o">&gt;</span>
  661. <span class="o">.</span>
  662. <span class="o">.</span>
  663. <span class="o">.</span>
  664. <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="n">N</span><span class="o">&gt;</span>
  665. </pre></div>
  666. </div>
  667. <p>The name <code class="xref py py-class docutils literal notranslate"><span class="pre">BaseClassName</span></code> must be defined in a
  668. namespace accessible from the scope containing the
  669. derived class definition. In place of a base class name, other arbitrary
  670. expressions are also allowed. This can be useful, for example, when the base
  671. class is defined in another module:</p>
  672. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DerivedClassName</span><span class="p">(</span><span class="n">modname</span><span class="o">.</span><span class="n">BaseClassName</span><span class="p">):</span>
  673. </pre></div>
  674. </div>
  675. <p>Execution of a derived class definition proceeds the same as for a base class.
  676. When the class object is constructed, the base class is remembered. This is
  677. used for resolving attribute references: if a requested attribute is not found
  678. in the class, the search proceeds to look in the base class. This rule is
  679. applied recursively if the base class itself is derived from some other class.</p>
  680. <p>There’s nothing special about instantiation of derived classes:
  681. <code class="docutils literal notranslate"><span class="pre">DerivedClassName()</span></code> creates a new instance of the class. Method references
  682. are resolved as follows: the corresponding class attribute is searched,
  683. descending down the chain of base classes if necessary, and the method reference
  684. is valid if this yields a function object.</p>
  685. <p>Derived classes may override methods of their base classes. Because methods
  686. have no special privileges when calling other methods of the same object, a
  687. method of a base class that calls another method defined in the same base class
  688. may end up calling a method of a derived class that overrides it. (For C++
  689. programmers: all methods in Python are effectively <code class="docutils literal notranslate"><span class="pre">virtual</span></code>.)</p>
  690. <p>An overriding method in a derived class may in fact want to extend rather than
  691. simply replace the base class method of the same name. There is a simple way to
  692. call the base class method directly: just call <code class="docutils literal notranslate"><span class="pre">BaseClassName.methodname(self,</span>
  693. <span class="pre">arguments)</span></code>. This is occasionally useful to clients as well. (Note that this
  694. only works if the base class is accessible as <code class="docutils literal notranslate"><span class="pre">BaseClassName</span></code> in the global
  695. scope.)</p>
  696. <p>Python has two built-in functions that work with inheritance:</p>
  697. <ul class="simple">
  698. <li><p>Use <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> to check an instance’s type: <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">int)</span></code>
  699. will be <code class="docutils literal notranslate"><span class="pre">True</span></code> only if <code class="docutils literal notranslate"><span class="pre">obj.__class__</span></code> is <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> or some class
  700. derived from <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></li>
  701. <li><p>Use <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> to check class inheritance: <code class="docutils literal notranslate"><span class="pre">issubclass(bool,</span> <span class="pre">int)</span></code>
  702. is <code class="docutils literal notranslate"><span class="pre">True</span></code> since <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> is a subclass of <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>. However,
  703. <code class="docutils literal notranslate"><span class="pre">issubclass(float,</span> <span class="pre">int)</span></code> is <code class="docutils literal notranslate"><span class="pre">False</span></code> since <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> is not a
  704. subclass of <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></li>
  705. </ul>
  706. <section id="multiple-inheritance">
  707. <span id="tut-multiple"></span><h3><span class="section-number">9.5.1. </span>Multiple Inheritance<a class="headerlink" href="#multiple-inheritance" title="Permalink to this headline">¶</a></h3>
  708. <p>Python supports a form of multiple inheritance as well. A class definition with
  709. multiple base classes looks like this:</p>
  710. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DerivedClassName</span><span class="p">(</span><span class="n">Base1</span><span class="p">,</span> <span class="n">Base2</span><span class="p">,</span> <span class="n">Base3</span><span class="p">):</span>
  711. <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="mi">1</span><span class="o">&gt;</span>
  712. <span class="o">.</span>
  713. <span class="o">.</span>
  714. <span class="o">.</span>
  715. <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="n">N</span><span class="o">&gt;</span>
  716. </pre></div>
  717. </div>
  718. <p>For most purposes, in the simplest cases, you can think of the search for
  719. attributes inherited from a parent class as depth-first, left-to-right, not
  720. searching twice in the same class where there is an overlap in the hierarchy.
  721. Thus, if an attribute is not found in <code class="xref py py-class docutils literal notranslate"><span class="pre">DerivedClassName</span></code>, it is searched
  722. for in <code class="xref py py-class docutils literal notranslate"><span class="pre">Base1</span></code>, then (recursively) in the base classes of <code class="xref py py-class docutils literal notranslate"><span class="pre">Base1</span></code>,
  723. and if it was not found there, it was searched for in <code class="xref py py-class docutils literal notranslate"><span class="pre">Base2</span></code>, and so on.</p>
  724. <p>In fact, it is slightly more complex than that; the method resolution order
  725. changes dynamically to support cooperative calls to <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>. This
  726. approach is known in some other multiple-inheritance languages as
  727. call-next-method and is more powerful than the super call found in
  728. single-inheritance languages.</p>
  729. <p>Dynamic ordering is necessary because all cases of multiple inheritance exhibit
  730. one or more diamond relationships (where at least one of the parent classes
  731. can be accessed through multiple paths from the bottommost class). For example,
  732. all classes inherit from <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>, so any case of multiple inheritance
  733. provides more than one path to reach <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>. To keep the base classes
  734. from being accessed more than once, the dynamic algorithm linearizes the search
  735. order in a way that preserves the left-to-right ordering specified in each
  736. class, that calls each parent only once, and that is monotonic (meaning that a
  737. class can be subclassed without affecting the precedence order of its parents).
  738. Taken together, these properties make it possible to design reliable and
  739. extensible classes with multiple inheritance. For more detail, see
  740. <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>
  741. </section>
  742. </section>
  743. <section id="private-variables">
  744. <span id="tut-private"></span><h2><span class="section-number">9.6. </span>Private Variables<a class="headerlink" href="#private-variables" title="Permalink to this headline">¶</a></h2>
  745. <p>“Private” instance variables that cannot be accessed except from inside an
  746. object don’t exist in Python. However, there is a convention that is followed
  747. by most Python code: a name prefixed with an underscore (e.g. <code class="docutils literal notranslate"><span class="pre">_spam</span></code>) should
  748. be treated as a non-public part of the API (whether it is a function, a method
  749. or a data member). It should be considered an implementation detail and subject
  750. to change without notice.</p>
  751. <p id="index-1">Since there is a valid use-case for class-private members (namely to avoid name
  752. clashes of names with names defined by subclasses), there is limited support for
  753. such a mechanism, called <em class="dfn">name mangling</em>. Any identifier of the form
  754. <code class="docutils literal notranslate"><span class="pre">__spam</span></code> (at least two leading underscores, at most one trailing underscore)
  755. is textually replaced with <code class="docutils literal notranslate"><span class="pre">_classname__spam</span></code>, where <code class="docutils literal notranslate"><span class="pre">classname</span></code> is the
  756. current class name with leading underscore(s) stripped. This mangling is done
  757. without regard to the syntactic position of the identifier, as long as it
  758. occurs within the definition of a class.</p>
  759. <p>Name mangling is helpful for letting subclasses override methods without
  760. breaking intraclass method calls. For example:</p>
  761. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Mapping</span><span class="p">:</span>
  762. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
  763. <span class="bp">self</span><span class="o">.</span><span class="n">items_list</span> <span class="o">=</span> <span class="p">[]</span>
  764. <span class="bp">self</span><span class="o">.</span><span class="n">__update</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
  765. <span class="k">def</span> <span class="nf">update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
  766. <span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
  767. <span class="bp">self</span><span class="o">.</span><span class="n">items_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
  768. <span class="n">__update</span> <span class="o">=</span> <span class="n">update</span> <span class="c1"># private copy of original update() method</span>
  769. <span class="k">class</span> <span class="nc">MappingSubclass</span><span class="p">(</span><span class="n">Mapping</span><span class="p">):</span>
  770. <span class="k">def</span> <span class="nf">update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">keys</span><span class="p">,</span> <span class="n">values</span><span class="p">):</span>
  771. <span class="c1"># provides new signature for update()</span>
  772. <span class="c1"># but does not break __init__()</span>
  773. <span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">keys</span><span class="p">,</span> <span class="n">values</span><span class="p">):</span>
  774. <span class="bp">self</span><span class="o">.</span><span class="n">items_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
  775. </pre></div>
  776. </div>
  777. <p>The above example would work even if <code class="docutils literal notranslate"><span class="pre">MappingSubclass</span></code> were to introduce a
  778. <code class="docutils literal notranslate"><span class="pre">__update</span></code> identifier since it is replaced with <code class="docutils literal notranslate"><span class="pre">_Mapping__update</span></code> in the
  779. <code class="docutils literal notranslate"><span class="pre">Mapping</span></code> class and <code class="docutils literal notranslate"><span class="pre">_MappingSubclass__update</span></code> in the <code class="docutils literal notranslate"><span class="pre">MappingSubclass</span></code>
  780. class respectively.</p>
  781. <p>Note that the mangling rules are designed mostly to avoid accidents; it still is
  782. possible to access or modify a variable that is considered private. This can
  783. even be useful in special circumstances, such as in the debugger.</p>
  784. <p>Notice that code passed to <code class="docutils literal notranslate"><span class="pre">exec()</span></code> or <code class="docutils literal notranslate"><span class="pre">eval()</span></code> does not consider the
  785. classname of the invoking class to be the current class; this is similar to the
  786. effect of the <code class="docutils literal notranslate"><span class="pre">global</span></code> statement, the effect of which is likewise restricted
  787. to code that is byte-compiled together. The same restriction applies to
  788. <code class="docutils literal notranslate"><span class="pre">getattr()</span></code>, <code class="docutils literal notranslate"><span class="pre">setattr()</span></code> and <code class="docutils literal notranslate"><span class="pre">delattr()</span></code>, as well as when referencing
  789. <code class="docutils literal notranslate"><span class="pre">__dict__</span></code> directly.</p>
  790. </section>
  791. <section id="odds-and-ends">
  792. <span id="tut-odds"></span><h2><span class="section-number">9.7. </span>Odds and Ends<a class="headerlink" href="#odds-and-ends" title="Permalink to this headline">¶</a></h2>
  793. <p>Sometimes it is useful to have a data type similar to the Pascal “record” or C
  794. “struct”, bundling together a few named data items. The idiomatic approach
  795. is to use <a class="reference internal" href="../library/dataclasses.html#module-dataclasses" title="dataclasses: Generate special methods on user-defined classes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dataclasses</span></code></a> for this purpose:</p>
  796. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  797. <span class="nd">@dataclass</span>
  798. <span class="k">class</span> <span class="nc">Employee</span><span class="p">:</span>
  799. <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
  800. <span class="n">dept</span><span class="p">:</span> <span class="nb">str</span>
  801. <span class="n">salary</span><span class="p">:</span> <span class="nb">int</span>
  802. </pre></div>
  803. </div>
  804. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">john</span> <span class="o">=</span> <span class="n">Employee</span><span class="p">(</span><span class="s1">&#39;john&#39;</span><span class="p">,</span> <span class="s1">&#39;computer lab&#39;</span><span class="p">,</span> <span class="mi">1000</span><span class="p">)</span>
  805. <span class="gp">&gt;&gt;&gt; </span><span class="n">john</span><span class="o">.</span><span class="n">dept</span>
  806. <span class="go">&#39;computer lab&#39;</span>
  807. <span class="gp">&gt;&gt;&gt; </span><span class="n">john</span><span class="o">.</span><span class="n">salary</span>
  808. <span class="go">1000</span>
  809. </pre></div>
  810. </div>
  811. <p>A piece of Python code that expects a particular abstract data type can often be
  812. passed a class that emulates the methods of that data type instead. For
  813. instance, if you have a function that formats some data from a file object, you
  814. can define a class with methods <a class="reference internal" href="../library/io.html#io.TextIOBase.read" title="io.TextIOBase.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> and
  815. <a class="reference internal" href="../library/io.html#io.TextIOBase.readline" title="io.TextIOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> that get the
  816. data from a string buffer instead, and pass it as an argument.</p>
  817. <p>Instance method objects have attributes, too: <code class="docutils literal notranslate"><span class="pre">m.__self__</span></code> is the instance
  818. object with the method <code class="xref py py-meth docutils literal notranslate"><span class="pre">m()</span></code>, and <code class="docutils literal notranslate"><span class="pre">m.__func__</span></code> is the function object
  819. corresponding to the method.</p>
  820. </section>
  821. <section id="iterators">
  822. <span id="tut-iterators"></span><h2><span class="section-number">9.8. </span>Iterators<a class="headerlink" href="#iterators" title="Permalink to this headline">¶</a></h2>
  823. <p>By now you have probably noticed that most container objects can be looped over
  824. using a <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement:</p>
  825. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">element</span> <span class="ow">in</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="mi">3</span><span class="p">]:</span>
  826. <span class="nb">print</span><span class="p">(</span><span class="n">element</span><span class="p">)</span>
  827. <span class="k">for</span> <span class="n">element</span> <span class="ow">in</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="mi">3</span><span class="p">):</span>
  828. <span class="nb">print</span><span class="p">(</span><span class="n">element</span><span class="p">)</span>
  829. <span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="p">{</span><span class="s1">&#39;one&#39;</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">:</span><span class="mi">2</span><span class="p">}:</span>
  830. <span class="nb">print</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
  831. <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="s2">&quot;123&quot;</span><span class="p">:</span>
  832. <span class="nb">print</span><span class="p">(</span><span class="n">char</span><span class="p">)</span>
  833. <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;myfile.txt&quot;</span><span class="p">):</span>
  834. <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
  835. </pre></div>
  836. </div>
  837. <p>This style of access is clear, concise, and convenient. The use of iterators
  838. pervades and unifies Python. Behind the scenes, the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement
  839. calls <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> on the container object. The function returns an iterator
  840. object that defines the method <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">__next__()</span></code></a> which accesses
  841. elements in the container one at a time. When there are no more elements,
  842. <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">__next__()</span></code></a> raises 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> exception which tells the
  843. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> loop to terminate. You can call the <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">__next__()</span></code></a> method
  844. using the <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> built-in function; this example shows how it all works:</p>
  845. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;abc&#39;</span>
  846. <span class="gp">&gt;&gt;&gt; </span><span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
  847. <span class="gp">&gt;&gt;&gt; </span><span class="n">it</span>
  848. <span class="go">&lt;str_iterator object at 0x10c90e650&gt;</span>
  849. <span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
  850. <span class="go">&#39;a&#39;</span>
  851. <span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
  852. <span class="go">&#39;b&#39;</span>
  853. <span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
  854. <span class="go">&#39;c&#39;</span>
  855. <span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
  856. <span class="gt">Traceback (most recent call last):</span>
  857. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  858. <span class="w"> </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
  859. <span class="gr">StopIteration</span>
  860. </pre></div>
  861. </div>
  862. <p>Having seen the mechanics behind the iterator protocol, it is easy to add
  863. iterator behavior to your classes. Define an <a class="reference internal" href="../library/stdtypes.html#container.__iter__" title="container.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method which
  864. returns an object with a <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">__next__()</span></code></a> method. If the class
  865. defines <code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code>, then <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code> can just return <code class="docutils literal notranslate"><span class="pre">self</span></code>:</p>
  866. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Reverse</span><span class="p">:</span>
  867. <span class="w"> </span><span class="sd">&quot;&quot;&quot;Iterator for looping over a sequence backwards.&quot;&quot;&quot;</span>
  868. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
  869. <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="n">data</span>
  870. <span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
  871. <span class="k">def</span> <span class="fm">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  872. <span class="k">return</span> <span class="bp">self</span>
  873. <span class="k">def</span> <span class="fm">__next__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  874. <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
  875. <span class="k">raise</span> <span class="ne">StopIteration</span>
  876. <span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">-</span> <span class="mi">1</span>
  877. <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">index</span><span class="p">]</span>
  878. </pre></div>
  879. </div>
  880. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">rev</span> <span class="o">=</span> <span class="n">Reverse</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">)</span>
  881. <span class="gp">&gt;&gt;&gt; </span><span class="nb">iter</span><span class="p">(</span><span class="n">rev</span><span class="p">)</span>
  882. <span class="go">&lt;__main__.Reverse object at 0x00A1DB50&gt;</span>
  883. <span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">rev</span><span class="p">:</span>
  884. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">char</span><span class="p">)</span>
  885. <span class="gp">...</span>
  886. <span class="go">m</span>
  887. <span class="go">a</span>
  888. <span class="go">p</span>
  889. <span class="go">s</span>
  890. </pre></div>
  891. </div>
  892. </section>
  893. <section id="generators">
  894. <span id="tut-generators"></span><h2><span class="section-number">9.9. </span>Generators<a class="headerlink" href="#generators" title="Permalink to this headline">¶</a></h2>
  895. <p><a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">Generators</span></a> are a simple and powerful tool for creating iterators. They
  896. are written like regular functions but use the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement
  897. whenever they want to return data. Each time <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> is called on it, the
  898. generator resumes where it left off (it remembers all the data values and which
  899. statement was last executed). An example shows that generators can be trivially
  900. easy to create:</p>
  901. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">reverse</span><span class="p">(</span><span class="n">data</span><span class="p">):</span>
  902. <span class="k">for</span> <span class="n">index</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">):</span>
  903. <span class="k">yield</span> <span class="n">data</span><span class="p">[</span><span class="n">index</span><span class="p">]</span>
  904. </pre></div>
  905. </div>
  906. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">reverse</span><span class="p">(</span><span class="s1">&#39;golf&#39;</span><span class="p">):</span>
  907. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">char</span><span class="p">)</span>
  908. <span class="gp">...</span>
  909. <span class="go">f</span>
  910. <span class="go">l</span>
  911. <span class="go">o</span>
  912. <span class="go">g</span>
  913. </pre></div>
  914. </div>
  915. <p>Anything that can be done with generators can also be done with class-based
  916. iterators as described in the previous section. What makes generators so
  917. compact is that the <a class="reference internal" href="../library/stdtypes.html#iterator.__iter__" title="iterator.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> and <a class="reference internal" href="../reference/expressions.html#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> methods
  918. are created automatically.</p>
  919. <p>Another key feature is that the local variables and execution state are
  920. automatically saved between calls. This made the function easier to write and
  921. much more clear than an approach using instance variables like <code class="docutils literal notranslate"><span class="pre">self.index</span></code>
  922. and <code class="docutils literal notranslate"><span class="pre">self.data</span></code>.</p>
  923. <p>In addition to automatic method creation and saving program state, when
  924. generators terminate, they automatically raise <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>. In
  925. combination, these features make it easy to create iterators with no more effort
  926. than writing a regular function.</p>
  927. </section>
  928. <section id="generator-expressions">
  929. <span id="tut-genexps"></span><h2><span class="section-number">9.10. </span>Generator Expressions<a class="headerlink" href="#generator-expressions" title="Permalink to this headline">¶</a></h2>
  930. <p>Some simple generators can be coded succinctly as expressions using a syntax
  931. similar to list comprehensions but with parentheses instead of square brackets.
  932. These expressions are designed for situations where the generator is used right
  933. away by an enclosing function. Generator expressions are more compact but less
  934. versatile than full generator definitions and tend to be more memory friendly
  935. than equivalent list comprehensions.</p>
  936. <p>Examples:</p>
  937. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="n">i</span><span class="o">*</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span> <span class="c1"># sum of squares</span>
  938. <span class="go">285</span>
  939. <span class="gp">&gt;&gt;&gt; </span><span class="n">xvec</span> <span class="o">=</span> <span class="p">[</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">]</span>
  940. <span class="gp">&gt;&gt;&gt; </span><span class="n">yvec</span> <span class="o">=</span> <span class="p">[</span><span class="mi">7</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
  941. <span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">y</span> <span class="k">for</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">xvec</span><span class="p">,</span> <span class="n">yvec</span><span class="p">))</span> <span class="c1"># dot product</span>
  942. <span class="go">260</span>
  943. <span class="gp">&gt;&gt;&gt; </span><span class="n">unique_words</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="n">word</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">page</span> <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">line</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
  944. <span class="gp">&gt;&gt;&gt; </span><span class="n">valedictorian</span> <span class="o">=</span> <span class="nb">max</span><span class="p">((</span><span class="n">student</span><span class="o">.</span><span class="n">gpa</span><span class="p">,</span> <span class="n">student</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> <span class="k">for</span> <span class="n">student</span> <span class="ow">in</span> <span class="n">graduates</span><span class="p">)</span>
  945. <span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="s1">&#39;golf&#39;</span>
  946. <span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">))</span>
  947. <span class="go">[&#39;f&#39;, &#39;l&#39;, &#39;o&#39;, &#39;g&#39;]</span>
  948. </pre></div>
  949. </div>
  950. <p class="rubric">Footnotes</p>
  951. <dl class="footnote brackets">
  952. <dt class="label" id="id2"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
  953. <dd><p>Except for one thing. Module objects have a secret read-only attribute called
  954. <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> which returns the dictionary used to implement the module’s
  955. namespace; the name <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> is an attribute but not a global name.
  956. Obviously, using this violates the abstraction of namespace implementation, and
  957. should be restricted to things like post-mortem debuggers.</p>
  958. </dd>
  959. </dl>
  960. </section>
  961. </section>
  962. <div class="clearer"></div>
  963. </div>
  964. </div>
  965. </div>
  966. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  967. <div class="sphinxsidebarwrapper">
  968. <div>
  969. <h3><a href="../contents.html">Table of Contents</a></h3>
  970. <ul>
  971. <li><a class="reference internal" href="#">9. Classes</a><ul>
  972. <li><a class="reference internal" href="#a-word-about-names-and-objects">9.1. A Word About Names and Objects</a></li>
  973. <li><a class="reference internal" href="#python-scopes-and-namespaces">9.2. Python Scopes and Namespaces</a><ul>
  974. <li><a class="reference internal" href="#scopes-and-namespaces-example">9.2.1. Scopes and Namespaces Example</a></li>
  975. </ul>
  976. </li>
  977. <li><a class="reference internal" href="#a-first-look-at-classes">9.3. A First Look at Classes</a><ul>
  978. <li><a class="reference internal" href="#class-definition-syntax">9.3.1. Class Definition Syntax</a></li>
  979. <li><a class="reference internal" href="#class-objects">9.3.2. Class Objects</a></li>
  980. <li><a class="reference internal" href="#instance-objects">9.3.3. Instance Objects</a></li>
  981. <li><a class="reference internal" href="#method-objects">9.3.4. Method Objects</a></li>
  982. <li><a class="reference internal" href="#class-and-instance-variables">9.3.5. Class and Instance Variables</a></li>
  983. </ul>
  984. </li>
  985. <li><a class="reference internal" href="#random-remarks">9.4. Random Remarks</a></li>
  986. <li><a class="reference internal" href="#inheritance">9.5. Inheritance</a><ul>
  987. <li><a class="reference internal" href="#multiple-inheritance">9.5.1. Multiple Inheritance</a></li>
  988. </ul>
  989. </li>
  990. <li><a class="reference internal" href="#private-variables">9.6. Private Variables</a></li>
  991. <li><a class="reference internal" href="#odds-and-ends">9.7. Odds and Ends</a></li>
  992. <li><a class="reference internal" href="#iterators">9.8. Iterators</a></li>
  993. <li><a class="reference internal" href="#generators">9.9. Generators</a></li>
  994. <li><a class="reference internal" href="#generator-expressions">9.10. Generator Expressions</a></li>
  995. </ul>
  996. </li>
  997. </ul>
  998. </div>
  999. <div>
  1000. <h4>Previous topic</h4>
  1001. <p class="topless"><a href="errors.html"
  1002. title="previous chapter"><span class="section-number">8. </span>Errors and Exceptions</a></p>
  1003. </div>
  1004. <div>
  1005. <h4>Next topic</h4>
  1006. <p class="topless"><a href="stdlib.html"
  1007. title="next chapter"><span class="section-number">10. </span>Brief Tour of the Standard Library</a></p>
  1008. </div>
  1009. <div role="note" aria-label="source link">
  1010. <h3>This Page</h3>
  1011. <ul class="this-page-menu">
  1012. <li><a href="../bugs.html">Report a Bug</a></li>
  1013. <li>
  1014. <a href="https://github.com/python/cpython/blob/main/Doc/tutorial/classes.rst"
  1015. rel="nofollow">Show Source
  1016. </a>
  1017. </li>
  1018. </ul>
  1019. </div>
  1020. </div>
  1021. </div>
  1022. <div class="clearer"></div>
  1023. </div>
  1024. <div class="related" role="navigation" aria-label="related navigation">
  1025. <h3>Navigation</h3>
  1026. <ul>
  1027. <li class="right" style="margin-right: 10px">
  1028. <a href="../genindex.html" title="General Index"
  1029. >index</a></li>
  1030. <li class="right" >
  1031. <a href="../py-modindex.html" title="Python Module Index"
  1032. >modules</a> |</li>
  1033. <li class="right" >
  1034. <a href="stdlib.html" title="10. Brief Tour of the Standard Library"
  1035. >next</a> |</li>
  1036. <li class="right" >
  1037. <a href="errors.html" title="8. Errors and Exceptions"
  1038. >previous</a> |</li>
  1039. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  1040. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  1041. <li class="switchers">
  1042. <div class="language_switcher_placeholder"></div>
  1043. <div class="version_switcher_placeholder"></div>
  1044. </li>
  1045. <li>
  1046. </li>
  1047. <li id="cpython-language-and-version">
  1048. <a href="../index.html">3.12.0 Documentation</a> &#187;
  1049. </li>
  1050. <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
  1051. <li class="nav-item nav-item-this"><a href=""><span class="section-number">9. </span>Classes</a></li>
  1052. <li class="right">
  1053. <div class="inline-search" role="search">
  1054. <form class="inline-search" action="../search.html" method="get">
  1055. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  1056. <input type="submit" value="Go" />
  1057. </form>
  1058. </div>
  1059. |
  1060. </li>
  1061. <li class="right">
  1062. <label class="theme-selector-label">
  1063. Theme
  1064. <select class="theme-selector" oninput="activateTheme(this.value)">
  1065. <option value="auto" selected>Auto</option>
  1066. <option value="light">Light</option>
  1067. <option value="dark">Dark</option>
  1068. </select>
  1069. </label> |</li>
  1070. </ul>
  1071. </div>
  1072. <div class="footer">
  1073. &copy; <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation.
  1074. <br />
  1075. This page is licensed under the Python Software Foundation License Version 2.
  1076. <br />
  1077. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  1078. <br />
  1079. See <a href="/license.html">History and License</a> for more information.<br />
  1080. <br />
  1081. The Python Software Foundation is a non-profit corporation.
  1082. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  1083. <br />
  1084. <br />
  1085. Last updated on Oct 02, 2023.
  1086. <a href="/bugs.html">Found a bug</a>?
  1087. <br />
  1088. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.5.0.
  1089. </div>
  1090. </body>
  1091. </html>