PageRenderTime 55ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/Languages/IronPython/Public/Tutorial/Tutorial.htm

http://github.com/IronLanguages/main
HTML | 2821 lines | 2795 code | 26 blank | 0 comment | 0 complexity | f3649312a6d6a8ae14c1d3d28296cd5b MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
  4. <title>IronPython Tutorial</title>
  5. <link rel="stylesheet" type="text/css" href="../Doc/IronPython.css" />
  6. <style type="text/css">
  7. p.AntiVerify { display : none; }
  8. p.Code-Background { color : gray; }
  9. p.NoVerify-Background { color : gray; }
  10. p.Code-Highlighted { color : gray; }
  11. p.NoVerify-Highlighted { color : gray; }
  12. p.CodeSample { color:blue; }
  13. p.DOSCommand { color:green; }
  14. p.ExceptionExample { color:green; }
  15. p.ExceptionOutput {display : none; }
  16. p.HiddenCode { display : none; }
  17. p.HiddenOutput {display : none; }
  18. p.LooseVerify { display : none; }
  19. p.Stepnonumbering { text-indent: 2em; }
  20. p.TypedExample { color : green; }
  21. p.UserExample { color : green; }
  22. p.UserCode { color:green; }
  23. </style>
  24. </head>
  25. <body lang="EN-US">
  26. <div class="Section1">
  27. <p class="Title1">IronPython Tutorial</p>
  28. <p class="Title2">A tour of Python on .NET</p>
  29. <p class="Title2">&nbsp;</p>
  30. <hr />
  31. <p class="CopyrightText">Information in this document is subject to change without
  32. notice. The example companies, organizations, products, people, and events depicted
  33. herein are fictitious. No association with any real company, organization, product,
  34. person or event is intended or should be inferred. Complying with all applicable
  35. copyright laws is the responsibility of the user. Without limiting the rights
  36. under copyright, no part of this document may be reproduced, stored in or introduced
  37. into a retrieval system, or transmitted in any form or by any means (electronic,
  38. mechanical, photocopying, recording, or otherwise), or for any purpose, without
  39. the express written permission of Microsoft Corporation.</p>
  40. <p class="CopyrightText">&nbsp;</p>
  41. <p class="CopyrightText">Microsoft may have patents, patent applications, trademarked,
  42. copyrights, or other intellectual property rights covering subject matter in
  43. this document. Except as expressly provided in any written license agreement
  44. from Microsoft, the furnishing of this document does not give you any license
  45. to these patents, trademarks, copyrights, or other intellectual property.</p>
  46. <p class="CopyrightText">&nbsp;</p>
  47. <p class="CopyrightText">© Microsoft Corporation. All rights reserved.</p>
  48. <p class="CopyrightText">&nbsp;</p>
  49. <p class="CopyrightText">Microsoft, MS-DOS, MS, Windows, Windows NT, MSDN, Active
  50. Directory, BizTalk, SQL Server, SharePoint, Outlook, PowerPoint, FrontPage,
  51. Visual Basic, Visual C++, Visual J++, Visual InterDev, Visual SourceSafe, Visual
  52. C#, Visual J#,&nbsp; and Visual Studio are either registered trademarks or trademarks
  53. of Microsoft Corporation in the U.S.A. and/or other countries.</p>
  54. <p class="CopyrightText">&nbsp;</p>
  55. <p class="CopyrightText">Other product and company names herein may be the trademarks of their respective owners.</p>
  56. <hr />
  57. <p class="ContentsHeading">Contents</p>
  58. <p class="Toc1"><a href="#Intro">Introduction</a></p>
  59. <p class="Toc1">Tutorial 1: <a href="#T1">Basic IronPython</a></p>
  60. <p class="Toc2">Exercise 1: <a href="#T1.1">The IronPython interactive console</a></p>
  61. <p class="Toc3">Task 1: <a href="#T1.1.1">IronPython console</a></p>
  62. <p class="Toc3">Task 2: <a href="#T1.1.2">Built-in modules and interactive exploration</a></p>
  63. <p class="Toc3">Task 3: <a href="#T1.1.3">External Python modules</a></p>
  64. <p class="Toc2">Exercise 2: <a href="#T1.2">Using the standard .NET libraries from IronPython</a></p>
  65. <p class="Toc3">Task 1: <a href="#T1.2.1">Basic .NET library use</a></p>
  66. <p class="Toc3">Task 2: <a href="#T1.2.2">Working with .NET classes</a></p>
  67. <p class="Toc3">Task 3: <a href="#T1.2.3">Generics</a></p>
  68. <p class="Toc2">Exercise 3: <a href="#T1.3">Loading additional .NET libraries</a></p>
  69. <p class="Toc3">Task 1: <a href="#T1.3.1">Using System.Xml - AddReference</a></p>
  70. <p class="Toc3">Task 2: <a href="#T1.3.2">Mapack - Loading the .NET libraries - AddReferenceToFile</a></p>
  71. <p class="Toc2">Exercise 4: <a href="#T1.4">Obtaining and Using the Python Standard Library</a></p>
  72. <p class="Toc3">Task 1: <a href="#T1.4.1">Configuring IronPython to use the Python standard library</a></p>
  73. <p class="Toc1">Tutorial 2: <a href="#T2">Advanced IronPython</a></p>
  74. <p class="Toc2">Exercise 1: <a href="#T2.1">Events and Delegates</a></p>
  75. <p class="Toc3">Task 1: <a href="#T2.1.1">File System Watcher</a></p>
  76. <p class="Toc3">Task 2: <a href="#T2.1.2">Improving the event handler</a></p>
  77. <p class="Toc3">Task 3: <a href="#T2.1.3">Defining events in Python</a></p>
  78. <p class="Toc2">Exercise 2: <a href="#T2.2">Windows Forms</a></p>
  79. <p class="Toc3">Task 1: <a href="#T2.2.1">Simple Windows Forms application</a></p>
  80. <p class="Toc2">Exercise 3: <a href="#T2.3">Windows Presentation Foundation (Avalon)</a></p>
  81. <p class="Toc3">Task 1: <a href="#T2.3.1">Simple Avalon Application</a></p>
  82. <p class="Toc3">Task 2: <a href="#T2.3.2">Avalon calculator</a></p>
  83. <p class="Toc1">Tutorial 3: <a href="#T3">IronPython and COM interoperability</a></p>
  84. <p class="Toc2">Exercise 1: <a href="#T3.1">Use Word for Spell Checking</a></p>
  85. <p class="Toc3">Task 1: <a href="#T3.1.1">Accessing Word and Checking
  86. Spelling</a></p>
  87. <p class="Toc3">Task 2: <a href="#T3.1.2">Use Windows Form Dialog to Correct
  88. Spelling</a></p>
  89. <p class="Toc1">Tutorial 4: <a href="#T4">Debugging IronPython programs</a></p>
  90. <p class="Toc2">Exercise 1: <a href="#T4.1">Debugging IronPython programs</a></p>
  91. <p class="Toc3">Task 1: <a href="#T4.1.1">Debugging IronPython programs using Microsoft CLR Debugger</a></p>
  92. <p class="Toc1">Tutorial 5: <a href="#T5">Extending IronPython</a></p>
  93. <p class="Toc2">Exercise 1: <a href="#T5.1">Extending using C#</a></p>
  94. <p class="Toc3">Task 1: <a href="#T5.1.1">Implementing a simple class - constructor and ToString</a></p>
  95. <p class="Toc3">Task 2: <a href="#T5.1.2">Making the object enumerable</a></p>
  96. <p class="Toc3">Task 3: <a href="#T5.1.3">Adding a custom operator</a></p>
  97. <p class="Toc3">Task 4: <a href="#T5.1.4">Adding a delegate</a></p>
  98. <p class="Toc2">Exercise 2: <a href="#T5.2">Extending using Visual Basic.NET</a></p>
  99. <p class="Toc3">Task 1: <a href="#T5.2.1">Implementing a simple class - constructor and ToString</a></p>
  100. <p class="Toc3">Task 2: <a href="#T5.2.2">Making the object enumerable</a></p>
  101. <p class="Toc3">Task 3: <a href="#T5.2.3">Adding a custom operator</a></p>
  102. <p class="Toc3">Task 4: <a href="#T5.2.4">Adding a delegate</a></p>
  103. <p class="Toc1">Tutorial 6: <a href="#T7">Using Visual Studio to Edit .py
  104. Files and Debug Them</a></p>
  105. <p class="Toc2">Exercise 1: <a href="#T6.1">Setting up Visual Studio for
  106. IronPython Debugging</a></p>
  107. <p class="Toc3">Task 1: <a href="#T6.1.1">Setting up Visual Studio for
  108. IronPython Debugging</a></p>
  109. </div>
  110. <div class="Section2">
  111. <h1><a name="Intro">Introduction</a></h1>
  112. <p class="Normal">IronPython is the .NET implementation of the Python programming language
  113. (<a href="http://www.python.org">www.python.org</a>).&nbsp; It's a dynamically typed language with support
  114. for many programming paradigms such as imperative, object-oriented, and functional programming, and also allows
  115. you to seamlessly use existing .NET code.</p>
  116. <p class="Normal">&nbsp;</p>
  117. <p class="Normal">The goal of this tutorial is to quickly familiarize you with the
  118. IronPython console and to show you how to make use of the extensive .NET libraries
  119. available.&nbsp; This tutorial also shows you how to get started in more specialized
  120. areas such as interoperating with <a href="http://www.microsoft.com/com/default.mspx">COM</a>
  121. and extending IronPython with C# and/or Visual Basic.&nbsp; While we do explain some
  122. finer points of Python's syntax, this tutorial is NOT meant to be an introduction to
  123. Python itself, and if you're looking for that, we recommend you start with the tutorial at
  124. <a href="http://docs.python.org/tut/tut.html">www.python.org</a>
  125. or the often recommended book
  126. <a href="http://oreilly.com/catalog/9780596513986/"><i>Learning Python</i></a>
  127. by Mark Lutz and David Ascher. In addition,
  128. <a href="http://www.ironpythoninaction.com/"><i>IronPython in Action</i></a>
  129. by Michael Foord and Christian Muirhead is a definitive guide that includes
  130. a wealth of IronPython-specific information.<br><br>
  131. Some of the exercises in this tutorial require specific software installations.&nbsp;
  132. The prerequisites to successfully complete the whole tutorial are:</p>
  133. <ul type="disc">
  134. <li class="Normal">Microsoft .NET Framework Version 4.0
  135. <ul type="circle">
  136. <li class="Normal">Required to run IronPython.</li>
  137. <li class="Normal">Download from
  138. <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9cfb2d51-5ff4-4491-b0e5-b386f32c0992&amp;displaylang=en">here</a>.</li>
  139. </ul>
  140. </li>
  141. </ul>
  142. <ul>
  143. <li class="Normal">Visual Studio 2010
  144. <ul type="circle">
  145. <li class="Normal">Very useful for the C#/VB extending tutorials.</li>
  146. <li class="Normal">Separate .NET 4.0 installation is not required if
  147. Visual Studio 2010 is installed.</li>
  148. <li class="Normal">Download from
  149. <a href="http://www.microsoft.com/visualstudio">here</a>.</li>
  150. </ul>
  151. </li>
  152. <li class="Normal"><a name="Mapack">Mapack</a> (example assembly found
  153. on the internet)<ul>
  154. <li>Required for the turorial &quot;<a href="#T1">Basic IronPython</a>&quot;
  155. and exercise &quot;<a href="#T1.3">Loading additional .NET Libraries</a>&quot;.</li>
  156. <li>Download Mapack from
  157. <a href="http://www.lutzroeder.com/dotnet/">here</a> (direct link
  158. to the Mapack.zip download is
  159. <a href="http://www.lutzroeder.com/dotnet/Download.aspx?File=Mapack">here</a>).</li>
  160. <li>Extract Mapack.dll from the zip file directly into the Tutorial
  161. directory.</li>
  162. </ul>
  163. </li>
  164. </ul>
  165. <p class="Normal">&nbsp;</p>
  166. <p class="Body">This tutorial assumes that the IronPython distribution was uncompressed
  167. into the directory C:\IronPython.&nbsp; Please note that your individual setup may
  168. vary.</p>
  169. <p class="Body">This tutorial also assumes that you will launch the
  170. IronPython console (c:\ironpython\ipy.exe) from the tutorial directory.&nbsp;
  171. When the tutorials direct you to start the IronPython console from the tutorial directory,
  172. you should change to the tutorial directory (&gt;cd c:\ironpython\tutorial)
  173. and launch the console with the tutorial as your working directory (&gt;..\ipy.exe).</p>
  174. <a name="VS2005Note"></a>
  175. <p class="Body">&nbsp;</p>
  176. <h1><a name="T1">Tutorial 1: Basic IronPython</a></h1>
  177. <p class="Body">The emphasis of this tutorial is on the basic interaction with
  178. the IronPython interpreter and using the interactive environment to explore
  179. the .NET libraries.</p>
  180. <p class="Body">Estimated time to complete this tutorial: <b>30 minutes</b></p>
  181. <p class="Body">The objective of this tutorial is to launch the IronPython interpreter,
  182. explore the environment of the interactive console and use IronPython to interact
  183. with .NET libraries.</p>
  184. <p class="Body">The exercises in this tutorial are:</p>
  185. <ul>
  186. <li>
  187. <p class="ExerciseList"><a href="#T1.1">The IronPython interactive console</a></p>
  188. </li>
  189. <li>
  190. <p class="ExerciseList"><a href="#T1.2">Using the standard .NET libraries
  191. from IronPython</a></p>
  192. </li>
  193. <li>
  194. <p class="ExerciseList"><a href="#T1.3">Loading additional .NET libraries</a></p>
  195. </li>
  196. </ul>
  197. <h2><a name="T1.1">Exercise 1: The IronPython interactive console</a></h2>
  198. <p class="Body">In this exercise, you will start the IronPython interactive
  199. interpreter and perform simple tasks to become acquainted with the IronPython
  200. environment.</p>
  201. <p class="Normal">If you are familiar with using the Python interactive console,
  202. the import statement and exploring the Python interactive environment using
  203. dir() function and __doc__ attribute, you can <a href="#T1.2">skip this exercise</a>.</p>
  204. <h3><a name="T1.1.1">Task 1: IronPython console</a></h3>
  205. <ol>
  206. <li>
  207. <p class="Step">Start the IronPython console from the tutorial directory
  208. by changing to the tutorial directory (&gt;cd c:\ironpython\tutorial) and
  209. launching the console c:\ironpython\ipy.exe executable (&gt;..\ipy.exe).&nbsp;
  210. This is how you should always launch the console for the tutorials, but
  211. from now on, we'll just direct you to &quot;start the IronPython console from
  212. the tutorial directory&quot;.</p>
  213. </li>
  214. </ol>
  215. <p class="Code-Highlighted">IronPython 2.7 (2.7.10920.0) on .NET 4.0.30319.1<br />
  216. Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.</p>
  217. <p class="Code-Highlighted">&gt;&gt;&gt; _</p>
  218. <ol start="2">
  219. <li>
  220. <p class="Step">IronPython's console interfaces with the user in a standard
  221. Read-Eval-Print Loop, or REPL. This means that the console repeatedly reads
  222. user input, evaluates the statement, prints the result (if any), and awaits
  223. more input. Try it out by executing the simple statements listed below.
  224. <b>Note:</b> The input line starting with 'for' requires an extra press of
  225. the enter key afterwards as a signal to the interpreter that there are no
  226. more statements in the 'for' loop.</p>
  227. </li>
  228. </ol>
  229. <p class="TypedExample">2+2</p>
  230. <p class="TypedExample">print &quot;Hello World!&quot;</p>
  231. <p class="TypedExample">for i in range(3): print i</p>
  232. <p class="TypedExample">x = 10</p>
  233. <p class="TypedExample">print x</p>
  234. <p class="Stepnonumbering">&nbsp;</p>
  235. <p class="Stepnonumbering">After this step, the console window will contain
  236. the following text:</p>
  237. <p class="Code-Highlighted">&gt;&gt;&gt; 2+2</p>
  238. <p class="Code-Background">4</p>
  239. <p class="Code-Highlighted">&gt;&gt;&gt; print &quot;Hello World!&quot;</p>
  240. <p class="Code-Background">Hello World!</p>
  241. <p class="Code-Highlighted">&gt;&gt;&gt; for i in range(3): print i</p>
  242. <p class="Code-Highlighted">...</p>
  243. <p class="Code-Background">0<br />
  244. 1<br />
  245. 2</p>
  246. <p class="Code-Highlighted">&gt;&gt;&gt; x = 10<br />
  247. &gt;&gt;&gt; print x</p>
  248. <p class="Code-Background"></p>
  249. <p class="Code-Background">10</p>
  250. <p class="Code-Highlighted">&gt;&gt;&gt; </p>
  251. <ol start="3">
  252. <li>
  253. <p class="Step">The IronPython console supports multi-line statements, often
  254. used in function or class definitions.&nbsp; IronPython prompts for additional lines in a
  255. multi-line statement using:</p>
  256. </li>
  257. </ol>
  258. <p class="Code-Highlighted">...</p>
  259. <p class="Code-Background"></p>
  260. <p class="Body">&nbsp;</p>
  261. <p class="Stepnonumbering">One of the more unique aspects of Python is its sensitivity to whitespace at the
  262. beginning of a line. Unlike C, C# or Java, where blocks of code are grouped by curly brackets "{...}",
  263. blocks of code in Python are grouped based on their level of indentation.&nbsp; Every new block of code
  264. must be indented one more level than the previous block of code.&nbsp; Blocks of code are used for many
  265. constructs, including function and class definitions, the bodies of loops, 'if'...'elif'...'else' clauses,
  266. and 'try'...'except'...'finally' blocks. </p>
  267. <p class="Stepnonumbering">Define the 'add' function (note, you
  268. need to enter spaces before the 'return' statement):</p>
  269. <p class="TypedExample">def add(a, b):<br>
  270. &nbsp;&nbsp;&nbsp; return a + b</p>
  271. <p class="Stepnonumbering">To complete the function definition, press Enter
  272. once more at this point</p>
  273. <p class="TypedExample">add(3, 2)</p>
  274. <p class="TypedExample">add('Iron', 'Python')</p>
  275. <p class="Stepnonumbering">&nbsp;</p>
  276. <p class="Stepnonumbering">After this step, the console contents will be:</p>
  277. <p class="Code-Highlighted">&gt;&gt;&gt; def add(a, b):<br />
  278. ...&nbsp;&nbsp;&nbsp;&nbsp; return a + b<br />
  279. ...<br />
  280. &gt;&gt;&gt; add(3, 2)</p>
  281. <p class="Code-Background">5</p>
  282. <p class="Code-Highlighted">&gt;&gt;&gt; add(&quot;Iron&quot;, &quot;Python&quot;)</p>
  283. <p class="Code-Background">&#39;IronPython&#39;</p>
  284. <p class="Code-Highlighted">&gt;&gt;&gt; </p>
  285. <p class="Step">&nbsp;</p>
  286. <ol start="4">
  287. <li>
  288. <p class="Step">To exit the IronPython interactive console, type Ctrl+Z and Enter (alternatively,
  289. press F6 followed by Enter).</p>
  290. </li>
  291. </ol>
  292. <p class="TypedExample">^Z</p>
  293. <h3><a name="T1.1.2">Task 2: Built-in modules and interactive exploration</a></h3>
  294. <ol>
  295. <li>
  296. <p class="Step">Start the IronPython console from the tutorial directory
  297. (see <a href="#Intro">Introduction</a> for details).</p>
  298. </li>
  299. <li>
  300. <p class="Step">Using the built-in function dir(), list the contents of
  301. the IronPython environment:</p>
  302. </li>
  303. </ol>
  304. <p class="TypedExample">dir()</p>
  305. <p class="Stepnonumbering">The output in the console window will be:</p>
  306. <p class="Code-Highlighted">&gt;&gt;&gt; dir()</p>
  307. <p class="Code-Background">['__builtins__', '__doc__', '__name__']<br />
  308. </p>
  309. <ol start="3">
  310. <li>
  311. <p class="Step">IronPython comes with several built-in modules including 'sys', which is
  312. one of the most frequently used.&nbsp; Load the 'sys' module using the 'import' keyword:</p>
  313. </li>
  314. </ol>
  315. <p class="TypedExample">import sys</p>
  316. <ol start="4">
  317. <li>
  318. <p class="Step">The Python 'import' statement is similar to the 'using' statement
  319. of C# or 'Imports' statement of Visual Basic. The important difference is
  320. that the C# and VB statements bring the names from the imported namespace
  321. into the global namespace to be accessed directly. Pythons import doesnt
  322. do that automatically, unless it is used in conjunction with the 'from'
  323. keyword (more on this later). To access the names or attributes in an imported
  324. module, prefix them with the module's name:</p>
  325. </li>
  326. </ol>
  327. <p class="UserExample">sys.version</p>
  328. <ol start="5">
  329. <li>
  330. <p class="Step">Use the dir() function to explore the environment:</p>
  331. </li>
  332. </ol>
  333. <p class="TypedExample">dir()</p>
  334. <p class="Stepnonumbering" style="margin-left: 0.5in">The environment (global namespace) has changed, now
  335. it contains the 'sys' module:</p>
  336. <p class="Code-Highlighted">&gt;&gt;&gt; dir()</p>
  337. <p class="Code-Background">['__builtins__', '__doc__', '__name__', 'sys']</p>
  338. <ol start="6">
  339. <li>
  340. <p class="Step">Use the dir() function to explore the contents of the 'sys'
  341. module:</p>
  342. </li>
  343. </ol>
  344. <p class="TypedExample">dir(sys)</p>
  345. <p class="HiddenOutput">['__doc__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getrecursionlimit', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setdefaultencoding', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']</p>
  346. <ol start="7">
  347. <li>
  348. <p class="Step">Print the values of some of the 'sys' module attributes:</p>
  349. </li>
  350. </ol>
  351. <p class="TypedExample">sys.path</p>
  352. <p class="LooseVerify">['.', '%DLR_ROOT%\\Test', '%DLR_ROOT%\\Languages\\IronPython\\Public\\Tutorial', '%DLR_ROOT%\\Languages\\IronPython\\Tests', '%DLR_ROOT%\\Test\\IronPythonTutorial', '%DLR_ROOT%\\bin\\Debug\\Lib', '%DLR_ROOT%\\bin\\Debug\\DLLs', '%DLR_ROOT%\\bin\\Debug']</p>
  353. <p class="TypedExample">sys.executable</p>
  354. <p class="LooseVerify">'%DLR_ROOT%\\bin\\Debug\\ipy.exe'</p>
  355. <h3><a name="T1.1.3">Task 3: External Python modules</a></h3>
  356. <p class="Normal">This task uses the module 'first.py' located in the Tutorial
  357. folder.</p>
  358. <ol>
  359. <li>
  360. <p class="Step">Import the 'first.py' module located in the Tutorial directory:</p>
  361. </li>
  362. </ol>
  363. <p class="TypedExample">import first</p>
  364. <p class="Code-Background"></p>
  365. <p class="Stepnonumbering">Because you launched ipy.exe from there, the Tutorial directory appears
  366. in sys.path, telling IronPython to look there in its search for 'first.py'.</p>
  367. <ol start="2">
  368. <li>
  369. <p class="Step">Explore the 'first' module using dir():</p>
  370. </li>
  371. </ol>
  372. <p class="TypedExample">dir(first)</p>
  373. <p class="Code-Highlighted">&gt;&gt;&gt; dir(first)</p>
  374. <p class="Code-Background">['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'add', 'factorial', 'hi']</p>
  375. <ol start="3">
  376. <li>
  377. <p class="Step">Print the documentation for the 'add' and 'factorial' functions,
  378. using __doc__ attribute:</p>
  379. </li>
  380. </ol>
  381. <p class="TypedExample">first.add.__doc__</p>
  382. <p class="TypedExample">first.factorial.__doc__</p>
  383. <p class="Stepnonumbering">&nbsp;</p>
  384. <p class="Stepnonumbering">We will use the __doc__ attribute later to explore .NET
  385. methods and their parameter types.</p>
  386. <p class="Code-Highlighted">&gt;&gt;&gt; first.add.__doc__</p>
  387. <p class="Code-Background">&#39;add(a, b) -&gt; returns a + b&#39;</p>
  388. <p class="Code-Highlighted">&gt;&gt;&gt; first.factorial.__doc__</p>
  389. <p class="Code-Background">&#39;factorial(n) -&gt; returns factorial of n&#39;</p>
  390. <ol start="4">
  391. <li>
  392. <p class="Step">Call the methods in the 'first' module and print the contents
  393. of the 'hi' attribute</p>
  394. </li>
  395. </ol>
  396. <p class="TypedExample">first.add(1,2)</p>
  397. <p class="TypedExample">first.factorial(5)</p>
  398. <p class="TypedExample">first.hi</p>
  399. <p class="Stepnonumbering">The expected output is:</p>
  400. <p class="Code-Highlighted">&gt;&gt;&gt; first.add(1,2)</p>
  401. <p class="Code-Background">3</p>
  402. <p class="Code-Highlighted">&gt;&gt;&gt; first.factorial(5)</p>
  403. <p class="Code-Background">120</p>
  404. <p class="Code-Highlighted">&gt;&gt;&gt; first.hi</p>
  405. <p class="Code-Background">&#39;Hello from IronPython!&#39;</p>
  406. <ol start="5">
  407. <li>
  408. <p class="Step">Exit the IronPython Interactive console (Ctrl+Z or F6 followed
  409. by Enter)</p>
  410. </li>
  411. </ol>
  412. <h2><a name="T1.2">Exercise 2: Using the standard .NET libraries from IronPython</a></h2>
  413. <p class="Body">Much of IronPython's power arises from its ability to seamlessly
  414. access the wealth of .NET libraries. This exercise will demonstrate how the
  415. .NET libraries can be used from IronPython.</p>
  416. <p class="Body">In this exercise, you will use the standard .NET libraries from
  417. IronPython. </p>
  418. <h3><a name="T1.2.1">Task 1: Basic .NET library use</a></h3>
  419. <ol>
  420. <li>
  421. <p class="Step">Start the IronPython console from the tutorial directory
  422. (see <a href="#Intro">Introduction</a> for details).</p>
  423. </li>
  424. <li>
  425. <p class="Step">Using the 'import' keyword, import the .NET System namespace:</p>
  426. </li>
  427. </ol>
  428. <p class="TypedExample">import System</p>
  429. <p class="Code-Background"></p>
  430. <ol start="3">
  431. <li>
  432. <p class="Step">Explore the System.Environment class and access some of
  433. its properties:</p>
  434. </li>
  435. </ol>
  436. <p class="TypedExample">dir(System.Environment)</p>
  437. <p class="UserCode">System.Environment.OSVersion</p>
  438. <p class="TypedExample">System.Environment.CommandLine</p>
  439. <p class="Stepnonumbering">&nbsp;</p>
  440. <p class="Stepnonumbering">The expected output of these commands is as follows
  441. (with ellipsis for convenience):</p>
  442. <p class="Code-Highlighted">&gt;&gt;&gt; dir(System.Environment)</p>
  443. <p class="HiddenOutput">['CommandLine','CurrentDirectory','Equals','Exit','ExitCode','ExpandEnvironmentVariables','FailFast','GetCommandLineArgs','GetEnvironmentVariable','GetEnvironmentVariables','GetFolderPath','GetHashCode','GetLogicalDrives','GetType','HasShutdownStarted','Is64BitOperatingSystem','Is64BitProcess','MachineName','MemberwiseClone','NewLine','OSVersion','ProcessorCount','ReferenceEquals','SetEnvironmentVariable','SpecialFolder','SpecialFolderOption','StackTrace','SystemDirectory','SystemPageSize','TickCount','ToString','UserDomainName','UserInteractive','UserName','Version','WorkingSet','__all__','__class__','__delattr__','__doc__','__format__','__getattribute__','__hash__','__init__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__']</p>
  444. <p class="NoVerify-Background">['CommandLine', 'CurrentDirectory', ... '__subclasshook__']</p>
  445. <p class="Code-Highlighted">&gt;&gt;&gt; System.Environment.OSVersion</p>
  446. <p class="NoVerify-Background">&lt;System.OperatingSystem object at 0x000000000000002B [Microsoft Windows NT 6.0.6000.0]</p>
  447. <p class="Code-Highlighted">&gt;&gt;&gt; System.Environment.CommandLine</p>
  448. <p class="LooseVerify">'"%DLR_ROOT%\\Bin\\Debug\\ipy.exe"'</p>
  449. <p class="NoVerify-Background">'C:\\IronPython\\ipy.exe'</p>
  450. <ol start="4">
  451. <li>
  452. <p class="Step">The import statement can also be used to import contents of
  453. a class or module into the global namespace.&nbsp; Use the &quot;from ... import ...&quot;
  454. flavor of the import statement to do this, then use dir() to explore the contents of the
  455. global namespace.</p>
  456. </li>
  457. </ol>
  458. <p class="TypedExample">from System.Math import *</p>
  459. <p class="UserCode">dir()</p>
  460. <p class="HiddenCode">set1 = set(dir())
  461. set2 = set(dir(object))
  462. list(set1-set2)
  463. </p>
  464. <p class="HiddenOutput">
  465. ['Tan','Sin','Ceiling','Sinh','Atan','Tanh','__name__','Pow','Cos','Cosh','Abs','Round','Atan2','BigMul','Acos','DivRem','Truncate','E','Max','__builtins__','Log','Asin','Floor','PI','Log10','System','Sign','Exp','Min','IEEERemainder','Sqrt']</p>
  466. <p class="Stepnonumbering">Now you can call Math methods without having to specify
  467. the namespace and class name prefix:</p>
  468. <p class="TypedExample">Sin(PI/2)</p>
  469. <p class="Stepnonumbering">&nbsp;</p>
  470. <p class="Stepnonumbering">The expected output is:</p>
  471. <p class="Code-Highlighted">&gt;&gt;&gt; from System.Math import *</p>
  472. <p class="Code-Highlighted">&gt;&gt;&gt; dir()</p>
  473. <p class="NoVerify-Background">
  474. ['Abs', 'Acos', 'Asin', 'Atan', 'Atan2', 'BigMul', 'Ceiling', 'Cos', 'Cosh', 'DivRem', 'E', 'Equals', 'Exp', 'Floor', 'GetHashCode', 'GetType', 'IEEERemainder', 'Log', 'Log10', 'Max', 'Min', 'PI', 'Pow', 'Round', 'Sign', 'Sin', 'Sinh', 'Sqrt', 'System', 'Tan', 'Tanh', 'ToString', 'Truncate', '__builtins__', '__doc__', '__name__']</p>
  475. <p class="Code-Highlighted">&gt;&gt;&gt; Sin(PI/2)</p>
  476. <p class="Code-Background">1.0</p>
  477. <h3><a name="T1.2.2">Task 2: Working with .NET classes</a></h3>
  478. <ol>
  479. <li>
  480. <p class="Step">Import the contents of the &quot;System.Collections&quot; namespace
  481. into the global namespace:</p>
  482. </li>
  483. </ol>
  484. <p class="TypedExample">from System.Collections import *</p>
  485. <p class="Code-Background"></p>
  486. <ol start="2">
  487. <li>
  488. <p class="Step">Create instance of the Hashtable class and explore the instance
  489. using dir():</p>
  490. </li>
  491. </ol>
  492. <p class="TypedExample">h = Hashtable()</p>
  493. <p class="Code-Background"></p>
  494. <p class="UserCode">dir(h)</p>
  495. <p class="HiddenCode">set1 = set(dir(h))
  496. set2 = set(dir(object))
  497. list(set1-set2)</p>
  498. <p class="HiddenOutput">
  499. ['Keys','GetObjectData','Count','Contains','__getitem__','KeyEquals','hcp','Clone','SyncRoot','__setitem__','Remove','Clear','comparer','__len__','ContainsValue','Add','__add__','EqualityComparer','GetHash','IsFixedSize','ContainsKey','CopyTo','GetEnumerator','Synchronized','__iter__','IsReadOnly','__contains__','Item','Values','IsSynchronized','OnDeserialization']</p>
  500. <ol start="3">
  501. <li>
  502. <p class="Step">Insert&nbsp;a few elements into the hash table:</p>
  503. </li>
  504. </ol>
  505. <p class="TypedExample">h['a'] = 'IronPython'</p>
  506. <p class="Code-Background"></p>
  507. <p class="TypedExample">h['b'] = 'Tutorial'</p>
  508. <p class="Code-Background"></p>
  509. <p class="Stepnonumbering">&nbsp;</p>
  510. <p class="Stepnonumbering">IronPython supports the C#-style syntax for accessing
  511. the hash table elements.&nbsp; The same syntax applies to any indexable object (Arrays,
  512. Array lists etc):</p>
  513. <p class="TypedExample">h['a']</p>
  514. <p class="Stepnonumbering" style="page-break-after:avoid">&nbsp;</p>
  515. <p class="Stepnonumbering" style="page-break-after:avoid">The output of this
  516. step will be:</p>
  517. <p class="NoVerify-Highlighted" style="page-break-after:avoid">&gt;&gt;&gt; h['a'] = 'IronPython'<br />
  518. &gt;&gt;&gt; h['b'] = 'Tutorial'</p>
  519. <p class="Code-Highlighted" style="page-break-after:avoid">&gt;&gt;&gt; h['a']</p>
  520. <p class="Code-Background">'IronPython'</p>
  521. <ol start="4">
  522. <li>
  523. <p class="Step">Enumerate the contents of the hash table using the &quot;for
  524. ... in ...&quot; statement. The hash table elements are instances of &quot;DictionaryEntry&quot;
  525. class. Print the &quot;Key&quot; and &quot;Value&quot; properties of each entry:</p>
  526. </li>
  527. </ol>
  528. <p class="TypedExample">for e in h: print e.Key, ':', e.Value</p>
  529. <p class="Stepnonumbering">&nbsp;</p>
  530. <p class="Stepnonumbering">The expected output in the console is as follows. Note that
  531. the input line starting with 'for' requires an extra return or enter key press because
  532. the interpreter prompts for more statements in the loop's body.</p>
  533. <p class="Code-Highlighted">&gt;&gt;&gt; for e in h: print e.Key, ':', e.Value<br>
  534. ...</p>
  535. <p class="Code-Background">a : IronPython<br />
  536. b : Tutorial</p>
  537. <ol start="5">
  538. <li>
  539. <p class="Step">You can initialize the collection classes using instances
  540. of the built-in list or tuple data types as arguments.&nbsp; You can
  541. create a Python list by specifying the list of elements in square brackets: [1,2,3].&nbsp;
  542. You create tuples by specifying elements in the parentheses: (1,2,3).</p>
  543. </li>
  544. </ol>
  545. <p class="TypedExample">l = ArrayList([1,2,3])</p>
  546. <p class="Code-Background"></p>
  547. <p class="TypedExample">for i in l: print i</p>
  548. <p class="TypedExample">s = Stack((1,2,3))</p>
  549. <p class="TypedExample">while s.Count: s.Pop()</p>
  550. <p class="Stepnonumbering">&nbsp;</p>
  551. <p class="Stepnonumbering">The expected output is:</p>
  552. <p class="Code-Highlighted">&gt;&gt;&gt; l = ArrayList([1,2,3])<br />
  553. &gt;&gt;&gt; for i in l: print i<br>
  554. ...</p>
  555. <p class="Code-Background">1<br />
  556. 2<br />
  557. 3</p>
  558. <p class="Code-Background"></p>
  559. <p class="Code-Highlighted">&gt;&gt;&gt; s = Stack((1,2,3))<br />
  560. &gt;&gt;&gt; while s.Count: s.Pop()<br>...</p>
  561. <p class="Code-Background">3<br />
  562. 2<br />
  563. 1</p>
  564. <h3><a name="T1.2.3">Task 3: Generics</a></h3>
  565. <ol>
  566. <li>
  567. <p class="Step">Import the Generic collections from the System.Collections.Generic
  568. namespace:</p>
  569. </li>
  570. </ol>
  571. <p class="TypedExample">from System.Collections.Generic import *</p>
  572. <p class="Code-Background"></p>
  573. <ol start="2">
  574. <li>
  575. <p class="Step">To instantiate a generic class, the generic type arguments
  576. must be specified.&nbsp; IronPython uses the following syntax to specify the type
  577. arguments: generic_type[type_argument, ...].&nbsp; Create an instance of generic
  578. list of string:</p>
  579. </li>
  580. </ol>
  581. <p class="TypedExample">l = List[str]()</p>
  582. <p class="Code-Background"></p>
  583. <ol start="3">
  584. <li>
  585. <p class="Step">Add string values into the list. Since we created a list of
  586. string, adding strings is possible:</p>
  587. </li>
  588. </ol>
  589. <p class="TypedExample">l.Add(&quot;Hello&quot;)</p>
  590. <p class="Code-Background"></p>
  591. <p class="TypedExample">l.Add(&quot;Hi&quot;)</p>
  592. <p class="Code-Background"></p>
  593. <ol start="4">
  594. <li>
  595. <p class="Step">Try adding objects of types other than string:</p>
  596. </li>
  597. </ol>
  598. <p class="ExceptionExample">l.Add(3)</p>
  599. <p class="Code-Background"></p>
  600. <p class="ExceptionExample">l.Add(2.5)</p>
  601. <p class="Code-Background"></p>
  602. <p class="ExceptionExample">l.Add([1,2,3])</p>
  603. <p class="Code-Background"></p>
  604. <p class="Stepnonumbering">&nbsp;</p>
  605. <p class="Stepnonumbering">Obviously, adding non-strings will result in a type error:</p>
  606. <p class="Code-Highlighted">&gt;&gt;&gt; l.Add(3)</p>
  607. <p class="NoVerify-Background">Traceback (most recent call last):<br />
  608. &nbsp;&nbsp;File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br />
  609. TypeError: expected str, got int<br /></p>
  610. <p class="Code-Highlighted">&gt;&gt;&gt; l.Add(2.5)</p>
  611. <p class="NoVerify-Background">Traceback (most recent call last):<br />
  612. &nbsp;&nbsp;File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br />
  613. TypeError: expected str, got float<br /></p>
  614. <p class="Code-Highlighted">&gt;&gt;&gt; l.Add([1,2,3])</p>
  615. <p class="NoVerify-Background">Traceback (most recent call last):<br />
  616. &nbsp;&nbsp;File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br />
  617. TypeError: expected str, got list<br /></p>
  618. <ol start="5">
  619. <li>
  620. <p class="Step">Enumerate the generic collection:</p>
  621. </li>
  622. </ol>
  623. <p class="TypedExample">for i in l: print i</p>
  624. <p class="Stepnonumbering">&nbsp;</p>
  625. <p class="Stepnonumbering">The output will be:</p>
  626. <p class="Code-Highlighted">&gt;&gt;&gt; for i in l: print i<br>...</p>
  627. <p class="Code-Background">Hello<br />
  628. Hi</p>
  629. <p class="ExceptionOutput">TypeError: expected str, got int
  630. TypeError: expected str, got float
  631. TypeError: expected str, got list</p>
  632. <ol start="6">
  633. <li>
  634. <p class="Step">Exit the IronPython Interactive console (Ctrl+Z or F6 followed
  635. by Enter)</p>
  636. </li>
  637. </ol>
  638. <h2><a name="T1.3">Exercise 3: Loading additional .NET libraries</a></h2>
  639. <p class="Body">IronPython can directly import only some of the .NET libraries
  640. - the most commonly used ones.&nbsp; To use additional .NET libraries, they must be
  641. explicitly referenced.&nbsp; IronPython maintains a list of all referenced
  642. assemblies (see clr.References in Task 1).&nbsp; To add a reference to a .NET assembly,
  643. use the functions available in the built-in 'clr' module:</p>
  644. <ul>
  645. <li>
  646. <p class="Body"><b>clr.AddReference</b> adds a reference to the .NET assembly
  647. either by passing the .NET assembly object directly, or specifying the file
  648. name or the assembly name (full or partial). This function is provided primarily
  649. for the kind of interactive exploration we see in this Tutorial. We recommend
  650. using the following functions in your code modules, since they provide more control
  651. over which assembly gets loaded.</p>
  652. </li>
  653. <li>
  654. <p class="Body"><b>clr.AddReferenceToFile</b> adds a reference to the assembly
  655. specified by its file name. This function will load the assembly from the
  656. file regardless of the assembly version. As a result, it doesn't guarantee
  657. that the correct assembly version is being loaded. To guarantee that correct
  658. assembly version is being loaded, use clr.AddReferenceByName. Moreover,
  659. AddReferenceToFile requires that the assembly be located in a
  660. directory listed in sys.path.</p>
  661. </li>
  662. <li>
  663. <p class="Body"><b>clr.AddReferenceToFileAndPath</b> provides similar
  664. functionality to AddReferenceToFile. The difference is that it accepts
  665. absolute path and before loading the assembly, AddReferenceToFileAndPath
  666. adds the file path into sys.path.</p>
  667. </li>
  668. <li>
  669. <p class="Body"><b>clr.AddReferenceByName</b> adds a reference to the assembly
  670. specified by its full assembly name, for example: &quot;System.Xml, Version=2.0.0.0,
  671. Culture=neutral, PublicKeyToken=b77a5c561934e089&quot;.</p>
  672. </li>
  673. <li>
  674. <p class="Body"><b>clr.AddReferenceByPartialName</b> adds reference to the
  675. assembly by specifying a partial assembly name. This function cannot guarantee
  676. that the correct version of the assembly is being loaded. Use clr.AddReferenceByName
  677. to reference a specific version of the assembly.</p>
  678. </li>
  679. </ul>
  680. <h3><a name="T1.3.1">Task 1: Using System.Xml - AddReference</a></h3>
  681. <ol>
  682. <li>
  683. <p class="Step">Start the IronPython console from the tutorial directory
  684. (see <a href="#Intro">Introduction</a> for details).</p>
  685. </li>
  686. <li>
  687. <p class="Step">To import System.Xml, the reference to the assembly containing
  688. the Xml components must be first added to IronPython.&nbsp; Reference System.Xml
  689. using the following code&nbsp; (you can enter &quot;clr.References&quot; before
  690. and after the call to &quot;clr.AddReference&quot; to see it change if you want):</p>
  691. </li>
  692. </ol>
  693. <p class="TypedExample">import clr</p>
  694. <p class="Code-Background"></p>
  695. <p class="TypedExample">clr.AddReference('System.Xml')</p>
  696. <p class="Code-Background"></p>
  697. <p class="TypedExample">from System.Xml import *</p>
  698. <p class="Code-Background"></p>
  699. <p class="TypedExample">dir()</p>
  700. <p class="HiddenOutput">['ConformanceLevel','DtdProcessing','EntityHandling','Formatting','IHasXmlNode','IXmlLineInfo','IXmlNamespaceResolver','NameTable','NamespaceHandling','NewLineHandling','ReadState','Resolvers','Schema','Serialization','ValidationType','WhitespaceHandling','WriteState','XPath','XmlAttribute','XmlAttributeCollection','XmlCDataSection','XmlCharacterData','XmlComment','XmlConvert','XmlDateTimeSerializationMode','XmlDeclaration','XmlDocument','XmlDocumentFragment','XmlDocumentType','XmlElement','XmlEntity','XmlEntityReference','XmlException','XmlImplementation','XmlLinkedNode','XmlNameTable','XmlNamedNodeMap','XmlNamespaceManager','XmlNamespaceScope','XmlNode','XmlNodeChangedAction','XmlNodeChangedEventArgs','XmlNodeChangedEventHandler','XmlNodeList','XmlNodeOrder','XmlNodeReader','XmlNodeType','XmlNotation','XmlOutputMethod','XmlParserContext','XmlProcessingInstruction','XmlQualifiedName','XmlReader','XmlReaderSettings','XmlResolver','XmlSecureResolver','XmlSignificantWhitespace','XmlSpace','XmlText','XmlTextReader','XmlTextWriter','XmlTokenizedType','XmlUrlResolver','XmlValidatingReader','XmlWhitespace','XmlWriter','XmlWriterSettings','Xsl','__builtins__','__doc__','__name__','clr']</p>
  701. <ol start="3">
  702. <li>
  703. <p class="Step">Note that the clr.AddReference function accepts either System.Reflection.Assembly object or string
  704. as a parameter. The string parameter can
  705. be a full assembly name, a partial assembly name, or a file name. For more control
  706. over the assembly references, use the appropriate functions described
  707. above. </p>
  708. <p class="Step">For example, consider the following alternatives for the statement clr.AddReference('System.Xml') above:</p>
  709. </li>
  710. </ol>
  711. <p class="TypedExample">clr.AddReferenceByName('System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')</p>
  712. <p class="Code-Background"></p>
  713. <p class="TypedExample">clr.AddReferenceByPartialName('System.Xml')</p>
  714. <p class="Code-Background"></p>
  715. <ol start="4">
  716. <li>
  717. <p class="Step">Load the XML file 'load.xml' into the XmlDocument. The
  718. xml file contains sample savegame data from the IronPython sample 'Puzzle' .
  719. For direct viewing, the load.xml file is located in the Tutorial folder</p>
  720. </li>
  721. </ol>
  722. <p class="TypedExample">d = XmlDocument()</p>
  723. <p class="Code-Background"></p>
  724. <p class="TypedExample">d.Load('load.xml')</p>
  725. <p class="Code-Background"></p>
  726. <ol start="5">
  727. <li>
  728. <p class="Step">We can now query the document. Query for all the saved games using the query below:</p>
  729. </li>
  730. </ol>
  731. <p class="TypedExample">n = d.SelectNodes('//Puzzle/SavedGames/Game/@caption')</p>
  732. <p class="TypedExample">for e in n: print e.Value</p>
  733. <p class="Stepnonumbering">&nbsp;</p>
  734. <p class="Stepnonumbering">The output in the console window will be:</p>
  735. <p class="Code-Highlighted">&gt;&gt;&gt; n = d.SelectNodes('//Puzzle/SavedGames/Game/@caption')<br />
  736. &gt;&gt;&gt; for e in n: print e.Value<br>...</p>
  737. <p class="Code-Background">
  738. Seattle (default game)<br />
  739. New York<br />
  740. World<br />
  741. North America<br />
  742. </p>
  743. <ol start="6">
  744. <li>
  745. <p class="Step">(Optional) Import the 'xmlutil.py' module located in the
  746. Tutorial directory and use the function provided in the module to walk the
  747. contents of the Xml document:</p>
  748. </li>
  749. </ol>
  750. <p class="TypedExample">import xmlutil</p>
  751. <p class="TypedExample">for e in xmlutil.Walk(d): print e.Name, e.Value</p>
  752. <p class="HiddenOutput">#document None
  753. #comment *************************************************************************
  754. *
  755. * Copyright (c) Microsoft Corporation.&nbsp;
  756. *
  757. * This source code is subject to terms and conditions of the Apache License, Version 2.0. A&nbsp;
  758. * copy of the license can be found in the License.html file at the root of this distribution. If&nbsp;
  759. * you cannot locate the Apache License, Version 2.0, please send an email to&nbsp;
  760. * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound&nbsp;
  761. * by the terms of the Apache License, Version 2.0.
  762. *
  763. * You must not remove this notice, or any other, from this software.
  764. *
  765. *
  766. * ***************************************************************************&nbsp;
  767. Puzzle None
  768. SavedGames None
  769. Game None
  770. caption Seattle (default game)
  771. type a
  772. y 714
  773. x 327
  774. level 11
  775. dimension 3
  776. Game None
  777. caption New York
  778. type r
  779. y 1538
  780. x 1205
  781. level 12
  782. dimension 3
  783. Game None
  784. caption World
  785. type h
  786. y 0
  787. x 0
  788. level 2
  789. dimension 4
  790. Game None
  791. caption North America
  792. type a
  793. x 2
  794. y 5
  795. level 4
  796. dimension 3
  797. TopLeftPreviewTile None
  798. x -3
  799. y -3
  800. dimension 3
  801. level 5
  802. Cache None
  803. allow true</p>
  804. <p class="Stepnonumbering">The Walk function is a generator (a Python function
  805. that contains a &quot;yield&quot; statement). As the Walk function executes, it returns
  806. (yields) the XML nodes one by one to the caller, who is iterating over the generator.
  807. The source for the Walk function is:</p>
  808. <p class="CodeSample">def Walk(xml):</br>
  809. &nbsp;&nbsp;&nbsp; yield xml</br><br>
  810. &nbsp;&nbsp;&nbsp; if hasattr(xml, &quot;Attributes&quot;):<br />
  811. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; attrs = xml.Attributes<br />
  812. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if attrs:<br />
  813. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for attr in attrs:</br>
  814. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  815. yield attr</br><br>
  816. &nbsp;&nbsp;&nbsp; for child in xml:<br />
  817. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for c in Walk(child):</br>
  818. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  819. yield c</p>
  820. <ol start="7">
  821. <li>
  822. <p class="Step">Exit the IronPython Interactive console (Ctrl+Z or F6 followed
  823. by Enter)</p>
  824. </li>
  825. </ol>
  826. <h3><a name="T1.3.2">Task 2: Mapack - Loading the .NET libraries - AddReferenceToFile</a></h3>
  827. <p class="Normal">This task requires the Mapack.dll library for linear algebra computations.&nbsp;
  828. The library is not part of the IronPython distribution. See <a href="#Mapack">prerequisites</a>
  829. for download details.</p>
  830. <ol>
  831. <li>
  832. <p class="Step">Start the IronPython console from the tutorial directory
  833. (see <a href="#Intro">Introduction</a> for details).</p>
  834. </li>
  835. <li>
  836. <p class="Step">Use the clr.AddReferenceToFile function to load the Matrix
  837. library &quot;Mapack.dll&quot;:</p>
  838. </li>
  839. </ol>
  840. <p class="TypedExample">import clr</p>
  841. <p class="Code-Background"></p>
  842. <p class="TypedExample">clr.AddReferenceToFile(&quot;Mapack.dll&quot;)</p>
  843. <p class="Code-Background"></p>
  844. <p class="TypedExample">from Mapack import *</p>
  845. <p class="Code-Background"></p>
  846. <p class="TypedExample">dir()</p>
  847. <p class="Stepnonumbering">The expected output will be:</p>
  848. <p class="Code-Highlighted">&gt;&gt;&gt; import clr<br />
  849. &gt;&gt;&gt; clr.AddReferenceToFile(&quot;Mapack.dll&quot;)<br />
  850. &gt;&gt;&gt; from Mapack import *<br />
  851. &gt;&gt;&gt; dir()</p>
  852. <p class="Code-Background">['CholeskyDecomposition', 'EigenvalueDecomposition', 'LuDecomposition', 'Matrix', 'QrDecomposition', 'SingularValueDecomposition', '__builtins__', '__doc__', '__name__', 'clr']</p>
  853. <p class="StepNoNumbering"></p>
  854. <p class="StepNoNumbering">If you're having trouble getting this to work, make sure
  855. Mapack.dll is on the search path. One easy way to do this is to copy Mapack.dll into
  856. the Tutorial direcroty (or whichever directory you're running IronPython from).</p>
  857. <ol start="3">
  858. <li>
  859. <p class="Step">Instantiate the Matrix class:</p>
  860. </li>
  861. </ol>
  862. <p class="ExceptionExample">m = Matrix()</p>
  863. <p class="Code-Background"></p>
  864. <p class="Stepnonumbering">Oops, bad arguments for the constructor.&nbsp; In the next
  865. step, you'll learn how to discover which constructors are available.</p>
  866. <p class="Code-Highlighted">Traceback (most recent call last):<br />
  867. &nbsp;&nbsp;File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br />
  868. TypeError: Matrix() takes at least 1 argument (0 given)</p>
  869. <ol start="4">
  870. <li>
  871. <p class="Step">Using the __doc__ attribute, find out information about
  872. Matrix constructors:</p>
  873. </li>
  874. </ol>
  875. <p class="TypedExample">print Matrix.__new__.__doc__</p>
  876. <p class="Code-Highlighted">&gt;&gt;&gt; print Matrix.__new__.__doc__</p>
  877. <p class="Code-Background">__new__(cls: type, rows: int, columns: int)<br />
  878. __new__(cls:type, rows: int, columns: int, value: float)<br />
  879. __new__(cls:type, value: Array[Array[float]])
  880. </p>
  881. <ol start="5">
  882. <li>
  883. <p class="Step">Create instances of the Matrix class using the correct constructors
  884. and set some matrix elements manually.&nbsp; IronPython supports custom indexing
  885. on .NET classes. </p>
  886. </li>
  887. </ol>
  888. <p class="TypedExample">m = Matrix(2, 2, 1.2)</p>
  889. <p class="Code-Background"></p>
  890. <p class="TypedExample">n = Matrix(2,1)</p>
  891. <p class="Code-Background"></p>
  892. <p class="TypedExample">n[0,0] = 4</p>
  893. <p class="Code-Background"></p>
  894. <p class="TypedExample">print m</p>
  895. <p class="TypedExample">print n</p>
  896. <p class="Code-Highlighted">&gt;&gt;&gt; m = Matrix(2, 2, 1.2)<br />
  897. &gt;&gt;&gt; n = Matrix(2,1)<br />
  898. &gt;&gt;&gt; n[0,0] = 4<br />
  899. &gt;&gt;&gt; print m</p>
  900. <p class="Code-Background">1.2 0<br />
  901. 0 1.2<br />
  902. </p>
  903. <p class="Code-Highlighted">&gt;&gt;&gt; print n</p>
  904. <p class="Code-Background">4<br />
  905. 0<br />
  906. </p>
  907. <ol start="6">
  908. <li>
  909. <p class="Step">(Optional) IronPython also supports overloaded operators.
  910. Matrix provides implementations of operators +, - (binary and unary), *,
  911. and equality. You can see the Python representation of these operators
  912. (__eq__, __add__, __mul__, __sub__, ...) using dir():</p>
  913. </li>
  914. </ol>
  915. <p class="UserCode">dir(m)</p>
  916. <p class="HiddenCode">set1 = set(dir(m))
  917. set2 = set(dir(object))
  918. list(set1-set2)</p>
  919. <p class="HiddenOutput">
  920. ['FrobeniusNorm','InfinityNorm','Rows','__neg__','__radd__','Columns','__getitem__','Symmetric','__rmul__','Inverse','__rsub__','Solve','Clone','__setitem__','Multiply','Submatrix','Subtract','Random','__eq__','Diagonal','Trace','Negate','Add','Determinant','Norm1','__sub__','__add__','Transpose','Square','Item','__mul__','__ne__']</p>
  921. <ol start="7">
  922. <li>
  923. <p class="Step">Make simple calculations with the matrices:</p>
  924. </li>
  925. </ol>
  926. <p class="TypedExample">print m * n</p>
  927. <p class="TypedExample">print n.Transpose() * m</p>
  928. <p class="TypedExample">print m * 3</p>
  929. <p class="TypedExample">print n + -n</p>
  930. <p class="Stepnonumbering">The expected output of this step is:</p>
  931. <p class="Code-Highlighted">&gt;&gt;&gt; print m * n</p>
  932. <p class="Code-Background">4.8<br />
  933. 0<br /><br />
  934. </p>
  935. <p class="Code-Highlighted">&gt;&gt;&gt; print n.Transpose() * m</p>
  936. <p class="Code-Background">4.8 0…

Large files files are truncated, but you can click here to view the full file