[翻译] python Tutorial 之一
其中本人認(rèn)為存在疑問的或翻譯不當(dāng)之處會用原文中的內(nèi)容加以標(biāo)記,且本文內(nèi)容完全用于研
究和學(xué)習(xí)IronPython 之用,限于本人英文翻譯功底有限,如有錯誤,歡迎大家批評指正。
???? 原文鏈接如下:http://www.cnblogs.com/daizhj/articles/1245093.html
?
Introduction
?
???? IronPython 作為 Python 語言在.net平臺上的實現(xiàn)(www.python.org),它是一種動態(tài)
語言且支持許多編程范例[paradigms] ,諸如面向?qū)ο?#xff0c;也允許您使用.net代碼進(jìn)行編譯。
???? 本tutorial的目標(biāo)就是使您快速熟悉IronPython 控制臺(console),并向您展示如何有
效的使用擴展(extensive).net庫。這個 tutorial同時還會展示如何從一些特殊領(lǐng)域入手,
這些領(lǐng)域諸如COM的內(nèi)部操作,用C#擴展 IronPython ,以及嵌入式的IronPython 等。當(dāng)
然本tutorial決不是針對Python語言自身進(jìn)行介紹,如果您想查閱這方面的資料,我們推薦您
這本書。
????? 本tutorial所需要的運行環(huán)境如下:
- Microsoft .NET Framework Version 2.0 Redistributable Package (x86)
- Required to run IronPython.
- Download from here.
- 譯者注:本人機器上是.net3.5,也可運行部分的示例,所以大家不必非要下載2.0
- .NET Framework 2.0 Software Development Kit (SDK) (x86)
- Required for the COM interoperability, extending and embedding tutorials.
- Download from here.
- Microsoft WinFX Runtime Components (Avalon)
- Required for "Advanced IronPython" and "Embedding IronPython" tutorials.
- Download from here.
- Mapack (example assembly found on the internet)
- Required for the "Basic IronPython" tutorial, exercise "Loading .NET Libraries".
- Download Mapack from here (direct link to the Mapack.zip download is here).
- Extract Mapack.dll from the zip file directly into the Tutorial directory.
? ?? 譯者注:如果您本機上安裝的是vs2008 RTM(筆者的開發(fā)環(huán)境),那么你就可以跳過上面的幾個安裝
直接進(jìn)入到下面的正文了,而如果您安裝的是vs2005,那么請您檢查相應(yīng)的條件是否已不足。
????? 本tutorial假設(shè)IronPython的發(fā)布包已被解壓縮至C:\IronPython. 請注意您個人的安裝可能會存在
一定的差異。
?? ? 本tutorial假設(shè)您將會使用IronPython 控制臺功能。將tutorial指導(dǎo)您從tutorial目錄啟動控制臺程
序時,您應(yīng)該定位到tutorial目錄下(>cd c:\ironpython\tutorial) ,并運行控制臺程序(>..\ipy.exe)。
?
????? 譯者注:ipy.exe可以下面鏈接中直接下載,我這樣做主要是覺得園子里有些朋友可以只是想了解并試
用一下,并不想下載那個IronPython的源碼包或相應(yīng)的sdk等資源。???? 好了,讓我們開始正文吧。
?
?
Tutorial 1: 基本IronPython應(yīng)用
?
???? 本章節(jié)主要強調(diào)的是IronPython的interpreter ,以及與.NET 類庫的互動場景(environment )???? 本章節(jié)閱讀大概需要30分鐘
???? The objective of this tutorial is to launch the IronPython interpreter, explore the environment
of the interactive console and use IronPython to interact with .NET libraries.
???? The exercises in this tutorial are:
-
The IronPython interactive console
-
Using the standard .NET libraries from IronPython
-
Loading additional .NET libraries
練習(xí) 1: IronPython 交互控件臺
In this exercise, you will start the IronPython interactive interpreter and perform simple tasks
to become acquainted with the IronPython environment. If you are familiar with using the Python
interactive console, the import statement and exploring the Python interactive environment using
dir() function and __doc__ attribute, you can skip this exercise.
任務(wù) 1: IronPython console
從本Tutorial的路徑下啟動IronPython console(c:"ironpython"ipy.exe)。它將如在DOS窗口
下出現(xiàn)如下提示
IronPython 1.0 on .NET 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.
>>> _
運行下面的內(nèi)容(在每一條內(nèi)容之后,按下回車鍵都會打印(prints)一條結(jié)果)。
2+2
print "Hello World!"
for i in range(3): print i
x = 10
print x
?
?????? 運行完上面操作后,控制臺窗口將會顯示如下內(nèi)容:
?
>>> 2+2
4
>>> print "Hello World!"
Hello World!
>>> for i in range(3): print i
...
0
1
2
>>> x = 10
>>> print x
10
>>>
IronPython 控制臺支持多行聲明(multi-line statements),這經(jīng)常要進(jìn)行函數(shù)定義:
...
?????? Unlike C# or Java, where blocks of code are grouped by curly brackets "{...}", blocks
of code in Python are grouped based on their level of indentation.? Every new block of code
must be indented one more level than the previous block of code.? Blocks of code are used
for function and class definitions as well as 'if' statements and loops.
?
????
????? 例如:定義“add”方法(注:你需要在return 之前敲入空格符):
?
?? ? return a + b
?
????? 要完成函數(shù)定義,按下Enter鍵。
?
add(3, 2)
add("Iron", "Python")
?
????? 完成這一步后,控制臺內(nèi)容如下:
?
>>> def add(a, b):
...???? return a + b
...
>>> add(3, 2)
5
>>> add("Iron", "Python")
'IronPython'
>>>
?
要退出控制臺程序,按下Ctrl+Z 并回車即可(alternatively, press F6 followed by Enter).
^Z
Task 2: 內(nèi)置模塊和交互式探查(interactive exploration)
從tutorial路徑啟動IronPython 控制臺 (see Introduction for details).
使用內(nèi)置dir() 函數(shù), 列出IronPython 環(huán)境的內(nèi)容:
dir()
??????? 控制臺顯示如下:
?
>>> dir()
['__builtins__', '__doc__', '__name__']
IronPython 有幾個內(nèi)置模塊,經(jīng)常使用的是"sys". 引入"sys" 模塊使用 "import" 聲明:
import sys
Python 引入聲明與 C# 的 "using" 或Visual Basic的"Imports"聲明相似。
The important difference is that the C# and VB statements bring the names from the
imported namespace into the global namespace to be accessed directly. Python’s import
doesn’t do that.
要訪問引入模塊的名稱和屬性, 使用module名稱的前綴:
sys.version
使用dir()方法去顯示環(huán)境:
dir()
改變環(huán)境 (global namespace), 現(xiàn)在它包括"sys" 模塊:
>>> dir()
['__builtins__', '__doc__', '__name__', 'sys']
使用dir() 方法來顯示"sys" 模塊的內(nèi)容:
dir(sys)
打印出 "sys" 模塊屬性的一些值:
sys.path
sys.executable
Task 3: 外部 Python 模塊
本任務(wù)使用 "first.py" (文件)模塊位于Tutorial 路徑.
聲明 "first.py" 模塊(您可以運行在Tutorial 路徑下的ipy.exe,“first”將位于sys.path路徑下):
import first
用dir()函數(shù)顯示"first" 模塊:
dir(first)
>>> dir(first)
['__builtins__', '__file__', '__name__', 'add', 'factorial', 'hi']
為打印 "add" 和 "factorial" 函數(shù)文檔內(nèi)容,使用__doc__屬性:
first.add.__doc__
first.factorial.__doc__
?
?????? __doc__屬性可用于顯示 .NET 方法和它們的參數(shù)類型。
?
>>> first.add.__doc__
'add(a, b) - returns a + b'
>>> first.factorial.__doc__
'factorial(n) - returns factorial of n'
調(diào)用 "first" 模塊方法并打印“hi”屬性內(nèi)容
first.add(1,2)
first.factorial(5)
first.hi
?
?????? 輸出內(nèi)容為:
>>> first.add(1,2)
3
>>> first.factorial(5)
120
>>> first.hi
'Hello from IronPython!'
在控制臺下Ctrl+Z 或 F6 按回車退出。
Exercise 2: 使用標(biāo)準(zhǔn).NET 庫
???? IronPython 的能力在于它可以無縫訪問.NET 類庫。這個練習(xí)將會示范如何使用(標(biāo)準(zhǔn)).NET 類庫。
Task 1: 基本.NET 類庫使用
在tutorial路徑下啟動IronPython 控制臺 (see Introduction for details).
使用 "import" 聲明, 引入 .NET 系統(tǒng)名空間:
import System
顯示System.Environment 類并訪問其下面的屬性::
dir(System.Environment)
System.Environment.OSVersion
System.Environment.CommandLine
?
?????? 如下是其命令行的輸入:
?
>>> dir(System.Environment)
?
>>> System.Environment.OSVersion
<System.OperatingSystem object at 0x000000000000002B [Microsoft Windows NT 6.0.6000.0]
>>> System.Environment.CommandLine
'C:""IronPython""ipy.exe'
?
使用“from ... import ..." 引入相應(yīng)類庫聲明,并使用dir()顯示全局名空間內(nèi)容。
from System.Math import *
dir()
?
????? 現(xiàn)在您可以調(diào)用Math 方法,而不必指定名空間和類前綴:??
Sin(PI/2)
?
????? 顯示輸出為:
?
>>> from System.Math import *
>>> dir()
['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__']
>>> Sin(PI/2)
1.0
Task 2: 使用.NET 類
聲明“System.Collections”名空間到“全局名空間”內(nèi):
from System.Collections import *
創(chuàng)建 Hashtable 類實例并使用dir()顯示實例的內(nèi)容:
h = Hashtable()
dir(h)
在hash表中插入一些元素:
h["a"] = "IronPython"
h["b"] = "Tutorial"
?
??????? IronPython 支持C# 風(fēng)格語法來訪問hash表元素. 相同的語法可用于支持索引的對象(Arrays, Array lists etc):
?
h["a"]
?
??????? 上面的操作步驟將會顯示如下輸出:
?
>>> h["a"] = "IronPython"
>>> h["b"] = "Tutorial"
>>> h["a"]
'IronPython'
使用聲明"for ... in ..." 列舉hash表的內(nèi)容. hash 表元素作為"DictionaryEntry" 類實例.
打印"Key"和"Value"屬性:
for e in h: print e.Key, ":", e.Value
?
??????? 控制臺顯示如下輸入:
>>> for e in h: print e.Key, ":", e.Value
...
a : IronPython
b : Tutorial
你可以向python內(nèi)置列表傳遞參數(shù)來初始化集合類. 您可以通過[1,2,3]來創(chuàng)建指定元素來創(chuàng)
建Python 列表[1,2,3].??
You create tuples by specifying elements in the parentheses: (1,2,3).
l = ArrayList([1,2,3])
for i in l: print i
s = Stack((1,2,3))
while s.Count: s.Pop()
?
??????? 輸出如下:
?
>>> l = ArrayList([1,2,3])
>>> for i in l: print i
...
1
2
3
>>> s = Stack((1,2,3))
>>> while s.Count: s.Pop()
...
3
2
1
Task 3: 泛型
從System.Collections.Generic名空間中,來聲明泛型集合類:
from System.Collections.Generic import *
初始化泛型類實例, 其泛型類型參數(shù)必須被指定.? IronPython 使用如下語法來指定類型參數(shù):
generic_type[type_argument, ...] (泛型類型[類型參數(shù)]).? 創(chuàng)建泛型string列表實例:
l = List[str]()
添加字符串?dāng)?shù)據(jù)到列表中( 因為創(chuàng)建了字符串列表,可以進(jìn)行添加):
l.Add("Hello")
l.Add("Hi")
嘗試添加其它類型的數(shù)據(jù):
l.Add(3)
l.Add(2.5)
l.Add([1,2,3])
?
??????? 顯然,添加“非字符串”型數(shù)據(jù)會導(dǎo)致如下“類型錯誤”輸出:
>>> l.Add(3)
Traceback (most recent call last):
File , line unknown, in Initialize##40
TypeError: expected str, got int
遍歷泛型集合:
for i in l: print i
The output will be:
>>> for i in l: print i
...
Hello
Hi
TypeError: expected str, got int TypeError: expected str, got float TypeError: expected str, got list
按下Ctrl+Z 或 F6 回車,退出IronPython 控制臺。
想等全部翻譯結(jié)束后,將翻譯的各篇文章拼揍起來。
????? 感興趣的朋友可以通過EMAIL或在回復(fù)中與我聯(lián)系。
? ? ? 控制臺程序下載鏈接:http://www.cnblogs.com/files/daizhj/ipy.zip
?
轉(zhuǎn)載于:https://www.cnblogs.com/daizhj/archive/2008/07/21/1247345.html
總結(jié)
以上是生活随笔為你收集整理的[翻译] python Tutorial 之一的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人人开源代码生成器启报错
- 下一篇: 数据库的设计原则