关于本教程

本教程是关于什么的?

这个分为两部分的教程将向您介绍Jython脚本语言,并为您提供足够的知识以开始开发自己的基于Jython的应用程序。 Jython是已与Java平台无缝集成的Python实现。 Python是一种功能强大的面向对象的脚本语言,主要在UNIX环境中使用。

Jython非常有用,因为它在JVM上运行时提供成熟脚本语言的生产力功能。 与Python程序不同,Jython程序可以在支持JVM的任何环境中运行。 今天,这意味着大多数主要的计算系统,包括Microsoft Windows,Mac OS,包括所有Linux系统和所有IBM系统在内的大多数UNIX变体。

本教程详细介绍了Jython。 在本教程的前半部分,我们将介绍使用Jython的概念和编程基础,包括访问选项和文件编译,语法和数据类型,程序结构,过程语句和函数。 本教程的下半部分将从Jython中的面向对象编程的概念性介绍开始。 从那里,我们将继续进行更动手的讨论,其中包括类语句,属性和方法,抽象类以及运算符重载。 这个高级讨论还将包括Jython中的调试,字符串处理,文件I / O和Java支持。 本教程将逐步演示如何在Jython中构建可运行的GUI应用程序。

在本教程的开始,示例代码将非常简单,但是到下半部分结束时,您将使用完整的函数,类和程序来启动和运行。 本教程包括一组附录,详细介绍了Jython的内部工作原理。

我应该学习本教程吗?

本教程面向各个层次的软件开发人员,从临时涉猎者到专业人士。 它特别面向希望利用脚本语言的生产力优势的Java开发人员。 它还面向希望更轻松地进入Java开发世界的Visual Basic和C ++ / C#程序员。

我们将一起探讨使用Jython编写脚本的以下方面:

第1部分

  • 下载并安装
  • Jython的概念介绍
  • 从命令行与源文件一起工作
  • 语法和数据类型
  • 程序结构
  • 程序陈述
  • 功能

第2部分

  • 使用Jython进行面向对象的编程
  • 调试
  • Java支持
  • 字符串处理
  • 文件IO
  • 在Jython中构建GUI应用程序

要从讨论中受益,您应该熟悉至少一种过程编程语言和计算机编程的基本概念,包括命令行处理。 要充分利用Jython的功能,您还应该熟悉面向对象编程的基本概念。 由于Jython在JVM上运行,因此具有Java平台的工作知识也将很有帮助。 尽管这不是本教程的要求。

请注意,本教程是针对Windows系统的。 所有命令示例都将使用Windows语法。 在大多数情况下,相似的命令在UNIX系统上执行相同的功能,尽管不会演示这些命令。

工具,代码和安装要求

您必须在开发系统上安装Jython 2.1或更高版本才能完成本教程。 您的开发系统可以是与命令提示符结合使用的任何ASCII文本编辑器(例如Windows记事本)。 本教程包括有关在系统上获取和安装Jython的详细说明。

要使用Jython,您还必须在系统上安装Java运行时环境(JRE)。 建议您使用最新的JRE(在撰写本文时为1.4.2),但是Java 1.2或更高版本的任何版本都可以正常工作。 如果要在浏览器中使用Jython(即作为小程序),则必须至少对浏览器有JRE 1.1可用。 请参阅相关主题下载最新版本的Java开发工具包(JDK)的。

本教程中的所有代码示例均已在Windows 2000上的Sun Java 1.4.1 JRE上运行的Jython上进行了测试。示例在其他操作系统上的任何类似配置上均应保持不变。

入门

安装说明

在本节中,我们将逐步完成在开发系统上下载,安装和验证Jython的每个步骤。

下载Jython

您可以从Jython主页下载Jython 2.1。 您可以在下载页面上找到易于遵循的下载说明。

如前所述,本教程基于当前稳定的Jython级别(版本2.1)。 也可以从Jython主页获得更高级的开发级别。

安装Jython

安装Jython很简单:只需执行从Jython主页下载的类文件即可。 假设您已安装JRE并在当前目录(以下示例中为C:\)中具有下载的类文件,则以下命令将安装Jython(请注意, < java_home>是JRE的安装目录):

C:\><java_home>\bin\java jython-21

请按照安装应用程序的提示进行操作。 我建议您选择默认值,并选择c:\ Jython-2.1作为目标目录。

验证安装

要验证是否安装了Jython,请输入以下命令:

C:\>dir c:\Jython-2.1

结果应该是这样的清单:

Volume in drive C is C_DRIVE Volume Serial Number is ????-???? Directory of C:\Jython-2.1 --/--/---- --:--- <DIR> . --/--/---- --:--- <DIR> .. --/--/---- --:--- 1,873 ACKNOWLEDGMENTS --/--/---- --:--- <DIR> cachedir --/--/---- --:--- <DIR> com --/--/---- --:--- <DIR> Demo --/--/---- --:--- <DIR> Doc --/--/---- --:--- <DIR> installer --/--/---- --:--- 428 jython.bat --/--/---- --:--- 719,950 jython.jar --/--/---- --:--- 272 jythonc.bat --/--/---- --:--- <DIR> Lib --/--/---- --:--- 7,184 LICENSE.txt --/--/---- --:--- 18,178 NEWS --/--/---- --:--- <DIR> org --/--/---- --:--- 651 README.txt --/--/---- --:--- 4,958 registry --/--/---- --:--- <DIR> Tools --/--/---- --:--- 224,493 Uninstall.class 9 File(s) 977,987 bytes ? Dir(s) ??? bytes free

试运行

最后一步是确保配置了Jython。 要运行Jython,请输入以下命令开始:

C:\>c:\jython-2.1\jython

该命令应导致类似于此内容的介绍:

Jython 2.1 on java1.4.1_01 (JIT: null) Type "copyright", "credits" or "license" for more information.

最后,我们将退出Jython。 在Jython提示符下,输入以下命令:

>>> import sys; sys.exit()

或者,您可以按两次Ctrl + C。

让生活更方便

在结束本节入门之前,您应该只知道最后一件事。 您可以通过将Jython命令路径添加到PATH变量中而无需指定Jython命令路径( <d>:\jython-2.1 )。 现在,您只需在命令提示符下键入jython

Jython的基本概念和优点

什么是Jython?

如前所述,Jython是用Java语言编写并与Java平台集成的Python实现。 Python是一种脚本语言,经常在包括Linux在内的基于UNIX的系统中使用。 Python由Guido van Rossum发明,并于1991年引入开发人员社区。Jython当前支持级别2.1的Python语法。

什么是脚本语言?

与Java编程语言不同,Jython是一种脚本语言。 脚本语言通常定义如下:

  • 非常容易学习和编码
  • 表情简洁,功能强大
  • 具有创建运行的“程序”所需的最少结构
  • 支持交互式(一次命令)执行
  • 不需要编译步骤
  • 支持反射式编程
  • 支持功能编程
  • 支持动态执行源代码(即eval函数)
  • 运行外部程序

通常,可以说脚本语言比程序​​员的效率和性能更重视程序员的效率。 与Java语言之类的编程语言相比,Jython易于学习且代码编写效率高。

Jython也可以描述为一种敏捷语言。 敏捷语言通常被认为能够执行各种各样的任务,并且对许多不同类型的问题都很有用,易于使用,但是功能强大且富有表现力。 它们也是理想的快速原型语言。

Jython的优势

与其基于C的表亲Python一样,Jython最常用于开发小型程序和脚本。 它具有许多功能,可在几分钟内创建简单但实用的程序。 这并不意味着Jython不能用于大规模编程。 实际上,Jython支持复杂的打包方案,类似于Java语言。 凭借其面向对象的特性,Jython具有高度的可扩展性,并为有效的软件工程提供了最新的结构。

像Java语言一样,与其他脚本语言(如Perl和Rexx)不同,Jython从一开始就被设计为一种面向对象的语言。 因此,它提供了易于理解和使用的强大的面向对象编程(OOP)功能。

Jython的最大优势之一是它可以在任何JVM上运行,因此用Jython编码的应用程序可以在几乎任何计算系统上运行。

Jython和Java平台

Jython构建在Java平台上。 从平台的角度来看,Jython运行时只是另一个Java类。 如果查看JYTHON.BAT文件,这很明显,该文件以Jython解释器为其主要类启动Java运行时,如下所示:

@echo off rem This file generated by Jython installer rem JAVA_HOME=<java_home> rem rem collect all arguments into %ARGS% set ARGS= :loop if [%1] == [] goto end set ARGS=%ARGS% %1 shift goto loop :end %JAVA_HOME%\bin\java.exe -Dpython.home=C:\jython-2.1 -cp "C:\jython-2.1\jython.jar;%CLASSPATH%" org.python.util.jython %ARGS%

一切都被解释了

Jython的核心是一种解释性语言 。 在Jython中,没有Java和C ++中的预编译步骤。 每次运行Jython代码时,都会对其进行重新解释。 这样,可以非常快速地进行代码更改并进行测试。 Jython代码也可以交互输入(一次只能输入一行)。 此外,您可以动态构造Jython代码(即,作为字符串)并直接执行它。 这样可以实现Java编码中不可能的编码灵活性。

Jython解释器将Jython源转换为内部形式,以进行更有效的处理。 它在验证语法的第一遍过程中执行此操作。 一旦完成此过程,便会解释内部化的源。 Jython还在磁盘上缓存了此内部化的表单。 在Jython模块<name>.py的Java类文件中,缓存的文件将是<name>$py.class

口译确实有其缺点,尽管大多数都是次要的。 例如,使用未定义的变量不是编译器错误,因此只有在(和何时)执行使用该变量的语句时,才会检测到该错误。 尽管与编译语言相比这似乎是一个缺点,但是您可以编辑然后立即运行程序并遇到错误(如果存在)的事实弥补了这一缺陷。 一个简单的测试和调试过程所花费的时间与重复的编辑编译步骤消除错误所花费的时间一样多。

关于性能

因为Jython是可解释的,所以它可能比Java之类的编译语言要慢。 在大多数应用程序(例如脚本或GUI)中,这种差异很难引起注意。 在大多数情况下,Jython增强的设计和编码灵活性可以弥补任何较小的性能损失。

由于Jython代码是动态转换为Java字节代码的,因此Java平台的最新增强功能(例如JIT和Sun的HotSpot JVM)还可以消除许多性能问题。

为了进一步提高性能,可以用Java语言实现代码段并从Jython调用它们。 例如,您可以在Jython中对程序进行原型制作,测试它们,然后(在性能问题的情况下)将关键部分转换为Java代码。 该技术很好地结合了Jython和Java语言的功能,因为在Jython中进行原型设计比在Java中容易得多。 在本教程的第2部分中 ,我们将讨论有关将Java语言和Jython结合在一起的更多信息。

与Jython合作

使用Jython作为命令行解释器

使用Jython的最简单方法之一是作为命令行解释器。 这样,代码行一次只能输入一行,您可以立即看到结果。 这是学习Jython并以最小的开销尝试新的编码技术的理想方法。

我们将从简短的Jython交互式会话开始。 在“>>”之后输入以下命令 或“ ...”提示:

C:\>c:\jython-2.1\jython

您应该收到看起来像这样的输出:

Jython 2.1 on java1.4.1_01 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> 1 + 2 3 >>> "Hello" + "Goodbye" 'HelloGoodbye' >>> def fac(x): ... if x <= 1: return 1 ... return long(x) * fac(x-1) ... >>> fac(3) 6L >>> fac(100) 93326215443944152681699238856266700490715968264381621468592963895217599 99322991560894146397615651828625369792082722375825118521091686400000000 0000000000000000L >>> import sys; sys.exit(0) C:\>

通过此示例,您可以看到如何立即执行输入。 这包括简单的表达式和更复杂的操作,例如函数定义(即fac函数)。 定义的值和功能可立即使用。 还要注意,Jython通过long类型支持非常大的整数。

请注意,在上面的示例中, fac函数的缩进非常关键。 您将在本教程的后面部分中了解有关此要求的更多信息(请参阅Blocks )。

通过源文件使用Jython

如果Jython只接受命令行输入,那将不会有用。 因此,它也接受源文件。 Jython源文件以.py扩展名结尾。 Jython文件必须包含Jython语句序列。 表达式,例如1 + 2 ,不是有效的语句(它们执行但不产生显示的输出)。

要显示表达式,必须将它们放在print语句中。 因此,上一节中的序列可以在源文件中进行如下编码:

print 1 + 2 print "Hello" + "Goodbye" def fac(x): if x <= 1: return 1 return long(x) * fac(x-1) print fac(3) print fac(100)

上面的代码将产生与使用Jython作为命令行解释器中的示例相同的输出。 实际上,这些语句可能是交互式输入的(在fac函数后添加了一个空白行),并且将得到相同的输出。

打印声明

如上一节所示,我们使用print语句来打印表达式。 该语句具有以下形式:

print expression {, expression}... {,} -- or -- print

上面的print语句还可以包含用逗号分隔的表达式列表。 输出每个这样的表达式,并在它们之间自动添加一个空格。 这样print "Hello", "Goodbye"输出Hello Goodbye

如果print语句以逗号结尾,则不会输出换行符。 行print本身会输出换行。

“ Hello World”示例

在Jython中,最典型的示例程序Hello World是一个单行文件(例如hello.py),如下所示:

print "Hello World!"

要运行该程序,您将输入以下命令: C:\>c:\jython-2.1\jython hello.py

注意,.py扩展名是必需的。 否则,将出现“找不到文件”错误。 jython命令具有多个选项。 请参见Jython主页(在相关主题的更多信息)。

Jython源文件是模块

Jython源文件可以包含多个要执行的语句序列。 它们还可以包含函数(请参见Jython函数 )和类定义(我们将在本教程的第2部分中进一步讨论类定义)。 实际上,Jython源文件可以是模块 (稍后将在模块和软件包中进行更多介绍),这些模块可能不直接使用,而是由其他程序导入 。 单个源文件可以同时扮演两个角色。 在上一节中考虑文件的此变体:

def fac(x): if x <= 1: return 1 return long(x) * fac(x-1) if __name__ == "__main__": print 1 + 2 print "Hello" + "Goodbye" print fac(3) print fac(100)

同样,运行此文件将得到与以前相同的输出。 但是,如果将文件导入到仅想重用fac函数的另一个程序中,则不会执行if (请参阅if语句 )测试下的任何语句。

还要注意,每个模块都有一个名称。 从命令行直接执行的程序称为“ __main__ ”。 此功能可用于为每个模块创建测试用例。

编译Jython

可以将Jython源文件编译为Java源代码(它会自动编译为字节码)以生成独立的类或Java存档文件(JAR)文件。 这是创建直接从Java平台调用的Jython代码所必需的,例如在创建小程序或servlet时。 在不发布Jython源代码的情况下提供Jython应用程序也很有用。

可以使用jythonc命令将Jython编译成一个纯Java类,该类可以直接在任何JVM上运行(也就是说,假设Java CLASSPATH具有必要的Jython JAR)。 有关使用的详细信息jythonc看到Jython主页( 相关信息 )。

编译示例

我们将使用factor.py文件(请参阅下载 )作为示例独立程序。 要编译它,请使用以下命令:

c:\>c:\jython-2.1\jythonc factor.py

如果没有错误,将创建Java类文件factor.classfactor$_PyInner.class 。 您可以在下载中找到实际生成的Java源代码。 要运行此(现在为Java)应用程序,请使用以下命令:

c:\><java_home>\bin\java -cp .;c:\jython-2.1\jython.jar factor

结果输出应如下所示:

factor running... For -1 result = Exception - only positive integers supported: -1 For 0 result = 1 For 1 result = 1 For 10 result = 3628800 For 100 result = 93326215443944152681699238856266700490715968264381621468592963895217599 99322991560894146397615651828625369792082722375825118521091686400000000 0000000000000000 For 1000 result = 4023872600770937735437024 ... many digits removed ... 00000000000000000000

请注意,输出与直接使用factor.py程序生成的输出相同。

Jython基本数据类型

一切都是对象

与Java语言不同,Jython将一切(包括所有数据和代码)视为对象。 这意味着您可以使用Jython代码来操纵这些对象,从而使反射和函数式编程非常容易在Jython中完成。 有关更多信息,请参见附录G:Jython类型摘要 。

一些选择类型(例如数字和字符串)更方便地被视为值,而不是对象。 Jython也支持此概念。

Jython仅支持一个空值,保留名称为None

普通运营商

所有Jython数据类型都支持以下基本操作:

运作方式 测试用法 注释)
x and y 布尔值和x与y 如果x为假,则不评估y
返回x或y作为结果
x or y 布尔值或x与y 如果x为真,则不评估y
返回x或y作为结果
not x x的布尔取反 返回0或1
x < y 比较严格小于 返回0或1
x > y 比较严格大于 返回0或1
x <= y 比较小于或等于 返回0或1
x >= y 比较大于或等于 返回0或1
x == y 比较相等 返回0或1
x != y
x <> y
比较不相等 返回0或1
x is y 相同性 如果x与y是相同的对象,则返回1;否则返回1。 否则0
x is not y 明显 如果x与y不同,则返回1;否则返回1。 否则0

请注意,与Java语言不同,所有类型都是可比较的。 通常,如果操作数的类型不匹配,则结果不相等。 复杂类型上的小于或大于关系是一致的,但是任意的。

布尔类型

Jython没有单独的布尔类型。 以下各节中描述的所有其他类型都可以用作布尔值。 对于数字类型,零将被视为false,而所有其他值将被视为true。 对于结构化类型(即序列和图),空结构被视为false,其他则为true。 None值始终为false。

数值类型

数字是不可变的 (即创建后不可更改)对象,它们被视为值。 Jython支持三种数字类型,如下所示:

  • 整数没有小数部分。 整数有两种子形式:

    • 正常 :较小的值在-2 ** 31到2 ** 31-1范围内(例如Java int s)。

      示例:-1、0、1、10000

    • Long :大值仅受JVM的可用内存(例如Java BigInteger )限制。

      示例:-1L,0L,1L,10000000000000000000000000000000000000L

  • 浮点值可能具有小数部分。 浮点型支持与Java double类型相同的值。

    示例:0.0,-1.01、2.5004E-100,-35e100

  • 复数值是一对浮点值,称为实部和虚部。 如果x是复数,则x.real是实部,而x.imag是虚部。 任一部分都可以是0.0。 x.conjugate方法使用+x.real-x.imag生成新的复合体。

    示例:1J,-1j,1 + 2j,-3.7 + 2e5j

其他数字类型的操作和功能

数值类型支持以下附加操作和功能:

操作/功能 用法
-x 取反x(即0-x)
+x 位置-不变(即0 + x)
x + y 将y加到x
x - y 从x减去y
x * y x乘以y
x / y 用x除以y
x % y
divmod(x, y)
将x的模数乘以y
回报(x / y,x%y)
x ** y
pow(x, y)
将x提高到y的幂
将x提高到y的幂
abs(x) 如果x < 0,然后是-x; 其他x
int(x) 将x转换为整数
long(x) 将x转换为long
float(x) 将x转换为浮点数
complex(r, i)
complex(x)
将r和i转换为复数
将x转换为复数

注意:对于数字类型,操作数将提升为下一个更高的类型。 对于整数操作数,/,%和**得出整数结果。 对于intlongfloatcomplex转换函数, x可以是字符串或任何数字。

其他整数类型运算

整数类型支持以下附加操作:

运作方式 用法 注释)
x << y 将y左移x位 类似于x * pow(2,y)
x >> y 将x位右移y 类似于x / pow(2,y)
x & y 和x和y位 清除x中y中为0的位。
x | y 或x和y位 将x中的位设置为y中的1。
x ^ y X和Y位的XOR 将x中的1翻转为y
~x 反转x位 翻转所有位

附加的浮动类型功能

浮点类型支持以下附加功能(在math模块中):

功能 注释)
ceil(v)
floor(v)
计算v的上限和下限。
sin(v)
cos(v)
tan(v)
计算v的正弦,余弦和正切。
acos(v)
asin(v)
atan(v)
atan2(v, w)
计算v(或v / w)的反正弦,反余弦和反正切。
sinh(v)
cosh(v)
tanh(v)
计算v的双曲正弦,余弦和正切。
exp(v)
pow(v, w)
sqrt(v)
log(v)
log10(v)
计算v的幂和对数。
fabs(v) 计算v的绝对值。
fmod(v, w) 计算v和w的模数。 可能与v%w不同。
modf(v) 返回(作为元组(i,f))v的整数和小数部分(均为浮点数)。
frexp(v) 返回(作为元组(m,e))v的浮点数尾数和整数指数。结果是v == m * 2 ** e
ldexp(v, w) 计算v * 2 ** w (w必须是整数)。
hypot(v, w) 计算v和w的斜边(即sqrt(v * v + w * w) )。

数学模块示例

我们将运行一个示例,以演示上一节中的math模块中的功能。 有关更多信息,请参见import语句和格式化字符串和值 。

from math import * print "PI = %f, e = %f" % (pi, e) print "Sine of %f = %f" % (0.5, sin(0.5)) print "Cosine of %f = %f" % (0.5, cos(0.5)) print "Tangent of %f = %f" % (0.5, tan(0.5))

示例代码产生以下输出:

PI = 3.141593, e = 2.718282 Sine of 0.500000 = 0.479426 Cosine of 0.500000 = 0.877583 Tangent of 0.500000 = 0.546302

Jython系列

集合类型

通常,您将需要创建其他数据项的集合。 Jython支持两种主要的集合类型。 最基本的是序列类型,它是项目的有序集合。 序列支持几种子类型,例如字符串,列表和元组。 另一个是地图类型。 地图通过键值支持关联查找。 您将在本节中了解这两种类型。

序列类型

序列是项目的有序集合。 所有序列都是零索引的,这意味着第一个元素是元素零(0)。 索引与序列的长度(小于1)是连续的(即0、1、2、3,...)。 因此,序列类似于C和Java数组。

所有序列都支持索引 (或下标 )以选择子元素。 如果x是一个序列,则表达式x[n]选择该序列的第n个值。 诸如列表之类的可变序列支持赋值索引,这会导致元素被替换。 对于这些序列的表达x[n] = y替换Y X的第n个元素。

序列支持索引的扩展,称为slicing ,它选择一系列元素。 例如, x[1:3]选择第二到x的第三元件(结束索引是一个过去的选择)。 像索引一样,切片可用于赋值以替换多个元素。

在Jython中,序列是一个抽象概念,因为您不直接创建序列,而只是直接从序列派生子类型的实例。 任何序列子类型都具有为序列描述的所有功能。

生命的一部分

切片的许多有效形式概述如下。 假设x是一个包含10个元素(索引0到9)的序列。

样本表达 结果行动 注释
x[1] 选择索引1 与索引相同
x[1:2] 选择索引1 最终值是所选值之后的一
x[1:] 选择索引1到9 缺少值表示序列长度
x[:7] 选择索引0到6 缺少值表示零
x[:-1] 选择索引0到8 负索引由序列长度调整
x[-6:-3] 选择索引3到6 支持反向范围
x[:] 选择索引0到9 整个序列; 这是序列的副本
x[:1000] 选择索引0到9 序列末尾的引用是结束
x[-100:] 选择索引0到9 序列开始的参考是开始
x[::2] 选择索引0、2、4、6、8 第三个值跳过选择

序列运算符

Jython支持序列( x和y )之间的几种操作,如下所示:

操作员 用法
x + y 连接(或连接)序列 [1,2,3] + [4,5,6] -> [1,2,3,4,5,6]
i * x
x * i
重复序列 [1,2,3] * 3 > [1,2,3,1,2,3,1,2,3]
o in x
o not in x
包含测试 2 in (1,2,3) -> 1(真)
7 not in (1,2,3) -> 1(真)

序列功能

另外,可以将几个函数应用于任何序列( x ),如下所示:

功能 用法
len(x) 序列的长度(元素数) len(1,2,3)-> 3
min(x) 序列中的最小值 min(1,2,3)-> 1个
max(x) 序列中的最大值 max(1,2,3)-> 3

关于序列的最后说明

正如我前面提到的,Jython中的序列是一个抽象概念,因为您不直接创建序列,而只是直接从序列派生子类型的实例。 任何序列子类型都具有为序列描述的所有功能。 有几种序列子类型,如下所示:

  • 字符串是字符的不可变序列(请参见Strings )
  • 元组是任何数据类型的不可变序列(请参见元组 )
  • range是整数的不可变序列(请参见Ranges )
  • 列表是任何数据类型的可变序列(请参阅列表 )

弦乐

字符串是被视为值的不可变字符序列。 这样,字符串支持所有导致生成新字符串的不可变序列函数和运算符。 例如, "abcdef"[1:4]是新字符串"bcd" 。 有关字符串函数的更多信息,请参见附录B:字符串方法 。

Jython没有字符类型。 字符由长度为一的字符串表示(即一个字符)。

字符串文字是通过单引号或三引号定义的。 使用单引号定义的字符串不能跨行,而使用三引号定义的字符串可以跨行。 字符串可以用双引号(“)或单引号(')引起来。引号字符可以包含另一个未转义的引号字符或转义的引号字符(由反斜杠(\)引起)。请参阅附录A:转义字符以获取更多信息。

字符串示例

以下是一些示例字符串:

  • “这是一个字符串”
  • “这也是一个字符串”
  • “这是巴里的琴弦”
  • “ Barry撰写了《 Jython简介》!”
  • “这是带引号的字符串中的转义引号(\“)”
  • r“ \ s * xyx \ s *”-等效于“ \\ s * xyx \\ s”
  • u“第一位是\ u0031”(相对于“第一位是\ x31”)

请注意,倒数第二个示例显示了原始字符串 。 在原始字符串中,反斜杠字符按字面意义使用(也就是说,无需将反斜杠加倍即可获得反斜杠字符)。 此原始格式对于包含转义符的字符串(例如正则表达式)特别有用。 在本教程的第2部分中,我们将更多地讨论正则表达式。

最后一个示例显示了Unicode字符串以及如何创建Unicode转义值。 请注意,所有字符串都使用Unicode字符值(由JVM提供)存储。 此格式仅允许您输入Unicode字符值。

混合和长弦

为了方便起见,Jython解析器会自动将仅用空格分隔的多个字符串连接起来(就像存在+运算符一样)。 这使得输入长字符串以及在单个字符串中混合引号类型变得容易。 例如,这里的顺序文字:

"This string uses ' and " 'that string uses ".'

变成这个字符串:

This string uses ' and that string uses ".

三引号用于输入包含换行符的长字符串。 使用单引号定义的字符串不能跨行,而使用三引号定义的字符串可以跨行。 它们也可以用于输入混合了引号类型的短(单行)字符串。 例如,以下是一个长的多行字符串:

r"""Strings literals are defined by the use single or triple quoting. Strings defined using single quotes cannot span lines while strings using triple quotes can. A string may be enclosed in quotes (") or apostrophes ('). They may contain the other character un-escaped or the quoting character escaped (proceeded by the backslash (\) character."""

这是一个简短的混合引号字符串: '''This string uses ' and that string uses ".'''

格式化字符串和值

Jython字符串支持类似于C的printf的特殊格式化操作,但使用模(%)运算符。 右边的项目集在字符串中匹配的%x位置处替换为左边的字符串。 设置值通常是单个值,值的元组或值的字典。

格式规范的一般格式为:

%{(key)}{width}{.precision}x

这是格式项目的指南:

  • key :在提供的字典中查找的可选键
  • width :字段的最小宽度(对于较大的值将更长)
  • 精度 :任意小数点后的位数
  • x :所述格式代码(在附录H:格式代码中 )

例如

print "%s is %i %s %s than %s!" % ("John", 5, "years", "older", "Mark") print "Name: %(last)s, %(first)s" % {'first':"Barry", 'last':"Feigenbaum", 'age':18}

版画

John is 5 years older than Mark! Name: Feigenbaum, Barry

元组

元组是任何类型的不可变列表。 创建后,便无法更改。 元组可以是任何长度,并且可以包含任何类型的对象。 这里显示一些示例:

注释)
() 空元组
(1,) 具有一个元素(整数)的元组; 需要逗号来将元组与类似(1)的表达式区分开
(1, 'abc', 2, "def") 具有四个元素,两个整数和两个字符串的元组
((), (1,), (1,2), (1,2,3)) 一个元组 每个子列表均包含整数
(1, "hello", ['a','b','c'], "goodbye") 整数,字符串和字符串子列表的混合元组
v1 = 1; v2 = 10
(1, v1, v2, v1 + v2)
一个整数元组; 支持变量引用和表达式

请注意,尽管元组是不可变的,但其中的元素可能不是不变的。 特别是,可以更改嵌套列表(请参见List )和地图(请参见Maps和字典 )。

范围

为了实现迭代(请参见The for语句 ),Jython使用不可变的递增整数序列。 这些序列称为range 。 范围可以通过两个内置函数轻松创建:

  • range({start,} end {,inc})创建一个小的范围。
    该范围的所有元素都存在。
  • xrange({start,} end {,inc})创建一个大范围。
    仅根据需要创建元素。

范围从start (默认为0)到(但不包括end ,依次inc (默认为1)。 例如:

print range(10) # prints [0,1,2,3,4,5,6,7,8,9] print range(2,20,2) # prints [2,4,6,8,10,12,14,16,18] print range(10,0,-1) # prints [10,9,8,7,6,5,4,3,2,1]

清单

列表是任何类型的可变序列。 它们的长度可以增加或缩小,并且列表中的元素可以替换或删除。 列表可以是任意长度,并且可以包含任何类型的对象。 有关列表函数的更多信息,请参见附录C:列表方法 。 一些示例如下所示。

注释)
[] 空清单
[1] 具有一个元素的列表,一个整数
[1, 'abc', 2, "def"] 包含四个元素,两个整数和两个字符串的列表
[[],[1],[1,2],[1,2,3]] 清单清单; 每个子列表均包含整数
[1, "hello", ['a','b','c'], "goodbye"] 整数,字符串和字符串子列表的混合列表
v1 = 1; v2 = 10
[1, v1, v2, v1 + v2]
整数列表; 支持变量引用和表达式

堆栈和队列

列表支持后进/先出 (LIFO)栈和先入/先出 (FIFO)队列的概念。 使用列表x创建堆栈,使用x.pop() (或等效的x.pop(-1) )删除项目。 使用列表x创建队列,使用x.pop(0)删除项目。 要将元素添加到列表中,请使用x.append(item) 。 例如:

l = [1,2,3,4,5] # define a list l.append(6) # l is [1,2,3,4,5,6] w = l.pop() # w is 6, l is [1,2,3,4,5] x = l.pop(-1) # x is 5, l is [1,2,3,4] y = l.pop(0) # y is 1, l is [2,3,4] z = l.pop(0) # z is 2, l is [3,4]

清单理解

列表也可以通过称为列表推导的高级表示法创建。 列表推导是结合forif语句创建列表元素的列表。 有关更多信息,请参见for语句和if语句 。 以下是一些列表理解的示例:

结果列表
[x for x in range(10)] [0,1,2,3,4,5,6,7,8,9]
range(10)相同range(10)
[x for x in xrange(1000)] [0,1,2,...,997,998,999]
range(1000)相同range(1000)
[(x < y) for x in range(3) for y in range(3)] [0,1,1,0,0,1,0,0,0]
[x for x in range(10) if x > 5] [6,7,8,9]
[x ** 2 + 1 for x in range(5)] [1,2,5,10,17]
[x for x in range(10) if x % 2 == 0] [0,2,4,6,8]

地图和字典

映射类型支持一组可变的键/值对(称为items )。 映射不同于序列,尽管它们支持许多类似的操作。 它们与序列相似,因为它们是抽象的。 您只能使用map子类型,其中最常用的类型是dictionary 。 有关映射功能的更多信息,请参见附录D:映射方法 。

地图通过键值支持关联查找。 键可以是任何不可变的类型。 键在进行哈希处理时必须是不可变的(请参见附录E:内置函数 ),并且哈希值必须保持稳定。 常见的键类型是数字,字符串和具有不可变元素的元组。 值可以是任何类型(包括None )。 如果m是地图,则函数len(m)返回地图中的项目数。

映射像序列一样,支持下标,但是按键而不是索引。 例如,如果m是一个映射,则x = m["x"]从映射中获取一个值,而m["x"] = x向映射中添加或替换一个新值。

字典范例

以下是一些示例词典文字:

注释)
{} 空字典
{1:"one", 2:"two", 3:"three"} 具有三个将整数映射到名称的元素的字典
{"one":1, "two":2, "three":3} 具有三个将名称映射到整数的元素的字典
{"first':'Barry", "mi":"A", "last":"Feigenbaum"} 映射名称的字典
{"init":(1,2,3), "term":['x','y','z'], "data":{1:10,2:100.5}} 包含元组,列表和另一个字典的字典
t = (1,2,3); l = ['x','y','z']; d = {1:10,2:100.5}
{"init":t, "term":l, "data":d}
A dictionary containing a tuple, a list, and another dictionary; variable references and expressions are supported

As shown in Formatting strings and values , dictionaries are convenient for format mapping.

Jython program structure

File structure

As explained in the introduction, Jython programs are simply text files. These files contain statements that are interpreted as they are input (after a quick parsing for syntax errors). Other files can be effectively included into Jython programs by use of the import ( see Modules and packages ) and exec statements (see Dynamic code evaluation ).

评论

Jython has two forms of comments:

  • Remarks are comments introduced with the sharp (#) character. All text on the same line after the sharp is ignored. Remarks can start in any column.
  • Documentation comments are a string literal located immediately after the start of an externalized block, such as a module, class, or function. The string does not change the behavior of the block; yet the comment can be accessed via the special attribute __doc__ to create descriptions of the block.

A commentary example

The following example shows a function ( fac ) that has a documentation comment and two remarks. It also demonstrates how to access the documentation comment programmatically.

The code sequence

def fac(x): "The fac function computes the value x! (x factorial)" if x <= 1: return 1 # base case return long(x) * fac(x-1) # use recursion on reduced case : print fac.__doc__

results in the output

The fac function computes the value x! (x factorial)

Statement syntax

As you likely have gathered from the previous sections, Jython has a simple syntax. It more closely resembles English than languages like C and Java language. In particular, each source line is (generally) a single statement. Except for expression and assignment statements, each statement is introduced by a keyword name, such as if or for . You may have blank or remark lines between any statements.

You don't need to end each line with a semicolon but you may do so if desired. If you wish to include multiple statements per line, then a semicolon is needed to separate statements.

If required, statements may continue beyond one line. You may continue any line by ending it with the backslash character, as shown below:

x = "A looooooooooooooooooooooooooooooooong string " + \ "another looooooooooooooooooooooooooooooooong string"

If you are in the middle of a structure enclosed in parenthesis (()), brackets ([]) or curly braces ({}), you may continue the line after any comma in the structure without using a backslash. 这是一个例子:

x = (1, 2, 3, "hello", "goodbye", 4, 5, 6)

Identifiers and reserved words

Jython supports identifiers similar to C++ and Java names. Identifiers are used to name variables, functions, and classes, and also as keywords. Identifiers can be of any length. They must start with a letter (upper- or lowercase) or the underscore (_) character. They may contain any combination of letters, decimal digits, and the underscore. Some valid identifiers are abc , abc123 , _x , x_ , myName , and ONE . Some invalid identifiers are 123abc , $xyz , and abc pqr .

Note that names starting with underscore are generally reserved for internal or private names.

Jython also has several reserved words (or keywords ) which cannot be used as variable, function, or class names. They fall under the following categories:

  • Statement introducers : assert , break , class , continue , def , del , elif , else , except , exec , finally , for , from , global , if , import , pass , print , raise , return , try , and while .
  • Parameter introducers : as , import , and in .
  • Operators : and , in , is , lambda , not , and or .

Note that keywords can be used in special circumstances, such as names of methods. For instance, you might use a keyword to call a Java method with the same name as a Jython keyword. Improper keyword use will generally cause a SyntaxError .

积木

Blocks (or suites ) are groups of statements that are used where single statements are expected. All statements that can take a block of statements as a target introduce the block with the colon character. The following statements (or statement clauses) can take a block as their target: if , elif , else , for , while , try , except , def , and class . Either a single statement or small group of statements, separated by semicolons, may follow the colon on the same line, or a block may follow the statement indented on subsequent lines.

I highly recommend that you use spaces to indent. Using tabs can cause problems when moving between systems (or editors) with different tab stops. Do not mix tabs and spaces in the same source file. By convention, four spaces are used per level.

Note: All the lines in the outermost block of a module must start at column one; otherwise, a SyntaxError is created.

Example blocks

Unlike with C and the Java language, in Jython curly braces are not used to delimit blocks; indentation is used instead. 例如

# the following prints 0 through 10 on one line for i in range(10): # print next value print i, print # new line

outputs the line: 0 1 2 3 4 5 6 7 8 9.

The block that is the body of the for-loop is indicated by the indented code. All lines in the body (except for comments) must be indented to the same position. The same loop could be written as:

# the following prints 0 through 10 on one line for i in range(10): print i, # print next value print # new line

Visibility and scopes

Jython supports the following scopes:

  • Built-in symbols defined by the Jython runtime are always available unless redefined in another scope.
  • Global variables are visible to the an entire module, including functions and classes declared in the module. A dictionary of the variables in the current global scope can be accessed via the globals function.
  • Local function arguments and variables declared in a function body are visible to that block. A dictionary of the variable names in the current local scope can be accessed via the locals function. In a module and outside of any function, the local and global scopes are the same.

In general, variables are visible in the scope of the block they are declared in and in any function (see Jython functions ) defined in that scope. Variables can be declared only once per scope; subsequent use re-binds that variable. Unlike in C++ and the Java language, nested blocks inside functions do not start new scopes.

Dynamic code evaluation

Jython is distinguished from typical languages in its ability to dynamically create code and then execute it. For example, in a calculator application, the user can enter an expression in text form and Jython can directly execute the expression (assuming it follows Jython source rules).

To better understand how Jython interprets/evaluates dynamic code, consider the following:

v1 = 100; v2 = 200 l1 = [1, 2, v1, v2] d1 = {"simple":123, "complex":(v1, v2, l1)} expr = raw_input("Enter an expression:") print eval(expr) # evaluate and print the expression

Below are some sample expressions to evaluate using the code above and the results of those evaluations:

Input expression (entered as a string) 结果
'1234.56' 1234.56
'v1+v2' 300
'd1["simple"]' 123
'v1**2 + len(l1)' 10004

Eval, exec and execfile

The eval function is used to execute an expression that returns a value. The exec statement is used to evaluate a code block (one or more statements) that does not return a value. It takes a file, a string (often read from a file), or a function as its source operand. The execfile function executes a code block from a file. In effect it runs a subprogram.

The exec statement has the following form:

exec source {in globals {, locals}}

The execfile and eval functions have the following form:

execfile(filename, {globals {, locals}}) eval(expression, {globals {, locals}})

All three forms optionally take two dictionaries that define the global and local namespaces. See Visibility and scopes for more details on namespaces. If these dictionaries are omitted, the current local namespace (as provided by the locals function) and the current global namespace (as provided by the globals function) are used.

For example, if the dictionaries gd = {"one":1, "two":2} and ld = {"x":100, "y":-1} are used as namespaces, then this: print eval("one + two * 2 + x + y", gd, ld)

prints: 104 .

More details on the use of the eval function and exec statement are available in the Python Library Reference (see Related topics ).

Modules and importing

About modules and imports

Jython breaks programs down into separate files, called modules. Modules are reused by importing them into your code. Jython provides many modules for you to reuse (see Appendix F: Jython library summary ). Jython also allows you to reuse any Java class and API.

Modules and packages

A module is an executable Jython file that contains definitions (for variables, functions and/or classes). Modules are imported (executed and bound) into other programs/scripts or modules. It is necessary to import a module when the importing program or module needs to use some or all of the definitions in the imported module.

Jython packages are conceptually hierarchically structured sets of modules. They are implemented as directories that contain one or more modules and a special file, __init__.py , that is executed before the first module of the package is executed.

Modules and packages enable reuse of the extensive standard Jython and Java libraries. You can also create modules and packages for reuse in you own Jython applications. For more information on the available Jython modules see Appendix F: Jython library summary . For more information on the available Java libraries visit the Sun Microsystems' Java technology home page (in Related topics ).

The import statement

The import statement executes another file and adds some or all of the names bound in it to the current namespace (see Visibility and scopes ). The current namespace will generally be the global namespace in the importing file. All statements, including assignments, in the module are executed. The import statement comes in several forms:

import module {as alias} -- or -- from module import name {as alias} -- or -- from module import *

The module value names a Jython (.py) file or dotted-path to a Jython package. The name value selects specific names from the module. Module names are case sensitive. These arguments can be repeated. The optional alias value allows imported objects to be renamed.

Example imports

Below are some example import statements:

Comment(s)
import sys Import the sys module. All names in sys can be referenced by the prefix sys .
from sys import exc_info Imports the exc_info function from the sys module. No prefix is needed.
from sys import * Imports all the names and functions in the sys module. No prefix is needed.
from sys import exc_info as einfo Imports the exc_info function from the sys module and names it einfo . No prefix is needed.
from string import uppercase as uc, lowercase as lc Imports the uppercase and lowercase functions from module string . No prefix is needed.
import sys, string Imports modules sys and string
import com.ibm.tools.compiler as compiler Imports the compiler module from the com.ibm.tools package giving it the short name compiler .

Importing modules and packages

To import a module or package, Jython must be able to find the associated source (.py) file. Jython uses the python.path (very similar to the Java language's CLASSPATH ) and python.prepath variables in the Jython registry to search for these files. You can use any text editor to add to or update the registry file in the Jython home directory (usually c:\jython-2.1 ). For more information, see the Jython registry (in Related topics ) or the registry file itself.

By default, Jython will search the directory containing the executing source file; thus, modules located in the same directory as the importing Jython program can be found. Frequently the current directory is also on the path. Simply enter the following command to examine the current search paths:

import sys print sys.path

On my machine, when running in the C:\Articles directory, the above command produces the following output:

['', 'C:\\Articles\\.', 'C:\\jython-2.1\\Lib', 'C:\\jython-2.1']

To find Java class files, Jython searches both the Java CLASSPATH and the sys.path values.

Import is executable

Unlike in the Java language, the import statement is executable and is not a compiler directive in Jython. Thus, imports do not need to be done at the start of a module; just sometime before the imported symbols are used. In fact importing can be done conditionally, as in the following example.

: # lots of other stuff : if __name__ == "__main__": : from sys import exit exit(0)

Imports can also be undone, as shown here:

import sys : # lots of other stuff : del sys

Subsetting imports

When you import modules, all values assigned or functions created in the module are usually available for reference by the module importer. You can prevent this by altering the code within the module. Either start the name with an underscore (_) or define a special variable, __all__ , at the start of the module, listing only the names of the variables or functions you want to be imported. For example, the __all__ definition below:

__all__ = ["getline","clearcache","checkcache"]

would only import the names getline , clearcache , and checkcache .

A similar strategy can be used at the module directory level. Defining the variable __all__ in a file called __init__.py instructs the interpreter as to which modules to import from the package if the wildcard (*) is used in the import statement. For instance, if the line __all__ = ['mod1', 'mod3', 'globals'] is in a file called __init__.py in a directory named modules , it will cause the statement from modules import * to import the modules mod1 , mod3 , and globals from the modules directory.

Running native applications

Using the os.system function, Jython can also run any external program that can be found on the current host PATH , such as a host operating system application. For example, to compile a Java program you could use

import os import sys cmd = "javac %(name)s.java 1>%(name)s.out 2>%(name)s.err" % \ {'name': sys.argv[1]}) rc = os.system(cmd) if rc == 0: print "Successful" else: print "Failed: return code=%i..." % rc # read and process the .err file...

Jython exceptions

About exceptions

Regardless of how much care a programmer takes in designing and testing his or her code, unexpected errors, or exceptions , can occur. Jython provides excellent support for recovering from these errors,

Exceptions are generally subclasses of the Jython type exceptions.Exception or the Java class java.lang.Exception . Most Jython exception names end in "Error" (such as IOError or IndexError ) or "Warning." Java exceptions end in either "Error" (for critical exceptions) or "Exception" (for generally recoverable exceptions). For more information see The Jython exception hierarchy or the Python Library Reference (see Related topics for a link).

The Jython exception hierarchy

Here is Jython's principle exception hierarchy subset.

  • 1 Exception

    • 1.1 SystemExit
    • 1.2 StopIteration
    • 1.3 StandardError
      • 1.3.1 KeyboardInterrupt
      • 1.3.2 ImportError
      • 1.3.3 EnvironmentError
        • 1.3.3.1 IOError
        • 1.3.3.2 OSError
      • 1.3.4 EOFError
      • 1.3.5 RuntimeError
        • 1.3.5.1 NotImplementedError
      • 1.3.6 NameError
        • 1.3.6.1 UnboundLocalError
      • 1.3.7 AttributeError
      • 1.3.8 SyntaxError
        • 1.3.8.1 IndentationError
        • 1.3.8.2 TabError
      • 1.3.9 TypeError
      • 1.3.10 AssertionError
      • 1.3.11 LookupError
        • 1.3.11.1 IndexError
        • 1.3.11.2 KeyError
      • 1.3.12 ArithmeticError
        • 1.3.12.1 OverflowError
        • 1.3.12.2 ZeroDivisionError
        • 1.3.12.3 FloatingPointError
      • 1.3.13 ValueError
      • 1.3.14 ReferenceError
      • 1.3.15 SystemError
      • 1.3.16 MemoryError
  • 2 Warning
    • 2.1 UserWarning
    • 2.2 DeprecationWarning
    • 2.3 PendingDeprecationWarning
    • 2.4 SyntaxWarning
    • 2.5 OverflowWarning
    • 2.6 RuntimeWarning
    • 2.7 FutureWarning

This hierarchy is a subset of the Python Library Reference (see Related topics ). These exceptions may be subclassed.

The try-except-else statement

Like C++ and the Java language, Jython supports exception handlers. These handlers are defined by the try-except-else statement, which has the following form:

try: statement except type, var: statement : else: statement -- or -- try: block except type, var: block : else: block

The except clause may be repeated with different type values. If so, the exceptions either must not overlap hierarchically (that is, be siblings) or they must be ordered from child to root exceptions. The optional type value is an exception type (either a subclass of exceptions.Exception or java.lang.Throwable ). If type is missing, then the except clause catches all Jython and Java exceptions. The optional var value receives the actual exception object. If var is missing, then the exception object is not directly accessible. The else clause is optional. It is executed only if no exception occurs.

If an exception occurs in the try clause, the clause is exited and the first matching except clause (if any) is entered. If no exception matches, the block containing the try-except-else is exited and the exception is re-raised.

If an exception is raised in the except or else clause, the clause will exit and the new exception will be processed in the containing block.

Accessing exception information

To access information about an exception, you may use the value provided in the except clause as described previously or the sys.exc_info function. For example, you can use the following function, in which type is the class of the exception, value is the exception object (use str(value) to get the message), and traceback is the execution trace back, which is a linked list of execution stack frames.

import sys : try: : except: type, value, traceback = sys.exc_info()

More details on the exceptions and trace backs is available in the Python Reference Manual (see Related topics ).

The try-finally statement

Like C++ and the Java language, Jython supports an additional construct, try-finally , which makes it easy to do required cleanup activities such as closing open files, releasing resources, etc. Any code in the finally clause is guaranteed to be executed once the try clause is entered, even if it is exited via a return statement (see The return statement ) or an exception. The try-finally statement has the following forms:

try: statement finally: statement -- or -- try: block finally: block

Note that try-except-else statements may nest in try-finally statements and vice versa.

A try statement example

Here is an example of using both try-except and try-finally statements together. We'll talk more about Jython file I/O in Part 2 of this tutorial.

def readfile (name): "return the lines in a file or None if the file cannot be read" try: file = open(name, 'r') # access the file try: return file.readlines() finally: file.close() # ensure file is closed except IOError, ioe: # report the error print "Exception -", ioe : # prints Exception - File not found - nofile (...) # then None print readfile("nofile") # prints a list of the lines in the file print readfile("realfile")

The raise statement

Exceptions are generated by called functions or built-in services. You can also generate one by using the raise statement. The raise statement has the following forms:

raise exception -- or -- raise exception_class {, message} -- or -- raise

Below are some example raise statements.

Comment(s)
raise Re-raise the current exception; used in an except block to regenerate the exception
raise IOError Create and raise an IOError with no message
raise anIOError Re-raise an existing IOError object
raise IOError, "End of File" Create and raise an IOError with a explanatory message
from java import io
raise io.IOException, "End of File"
Create and raise a Java exception with a explanatory message

Jython procedural statements

A statement for every procedure

Jython has a number of statements that perform computation or control program flow, including the expression , assignment , pass , if , while , for , break , continues , and del statements. You'll learn about these procedural statements in the sections that follow.

The pass statement

The pass statement is used where a Jython statement is required syntactically but when no action is required programmatically. pass can be useful to create empty loops or to provide a temporary implementation of a block. The statement has the following form:

pass

The expression statement

In Jython, any expression can serve as a statement; the resulting value is simply discarded. Most often any such expression statement calls a function or method (discussed further in Part 2). For example, the following code invokes three functions in sequence:

performAction(1) performAction(2) performAction(3)

Operators and precedence

Jython expressions consist of any valid combination of the operators described in Summary of operator precedence . They are similar to the expressions of most languages, especially C/C++ and the Java language.

1 + 1 # add 1 and 1 yielding 2 (1 + 2) ** 3 # add 1 and 2 and raise the result by 3 yielding 27 1 + 2 ** 3 # raise 2 by 3 and add 1 yielding 9 x % y == 0 # tests to see if x is divisible by y x & 1 # extracts the low-order bit of x # below is the same as: "(0 <= x) and (x < 100)" but is more concise 0 <= x < 100 # tests a range # the use of (...) below is not required but it improves readability (x > 0) and (y < 0) # tests the relation of 2 values 1 + 2 * 3 ** 4 << 2 # complex expression yielding 652 (1 + (2 * (3 ** 4))) << 2 # Equivalent fully parenthesized expression

Summary of operator precedence

Jython operator precedence is summarized in the table below. Use parentheses to change the order or to improve readability. Unless otherwise noted, within the same precedence level operations are evaluated left-to-right. Higher priority operations are at the top of the list.

运作方式 评论
( expression )
( expr1, ..., exprN )
[ expr1, ...,exprN ]
{ key1:value1, ..., keyN:valueN }
`expression`
Nested expression or grouping
Tuple constructor
List constructor
Dictionary constructor
repr (representation) expression
x.name
x[i], x[i:j], x[i:j:k]
x(...)
Member (attribute or method) selection
Subscripting or slicing
Function call
** Raise to power (right associative)
+
-
~
Posate
Negate
Bit-wise not
*
/
%
时报
Divide
Modulo
+
-

减去
<<, >> Bit-wise shifts
& Bit-wise and
^ Bit-wise xor
| Bit-wise or
is , is not
in , not in
< , <= , > , >= , == , != , <>
Sameness test
Containment test
Relational test
not Logical not
and Logical and
or Logical or
lambda Declare a lambda function

The assignment statement

The assignment statement is used to bind (or re-bind) a value to a variable. If not already defined, binding creates the variable and assigns it the value. In Jython all data are objects, so variables actually store references to objects, not values. Variables are not typed, thus an assignment can change the type of the value a variable references.

More than one variable can have a reference to the same object; this is called aliasing . For this reason, Jython supports the is and is not operators to test whether or not two variables refer to the same object.

A variable can only be declared once in a block. This means that it is declared (by the parser) in the block even if the flow in the block does not execute the assignment statement that creates it. The variables will have an undefined value until the first assignment is actually executed.

Note that like the assignment statement other statements can bind variables. Some examples are the class , def , for , and except statements.

Parallel assignment

The assignment statement supports sequence unpacking. This can achieve a form of parallel assignment. For example, the following sets a to 1 , b to 2 , and c to 3 :

(a, b, c) = (1, 2, 3) -- or -- x = (1, 2, 3) (a, b, c) = x

The same number of variables must be on the left side as on the right side. This unpacking can be very useful if you are provided with a sequence variable (say as an argument to a function) and want to access the values within it. For convenience, the enclosing parentheses are not required, so the above assignment could also be written as a, b, c = 1, 2, 3 .

Multiple assignment

Jython supports the use of multiple assignment. For example, the following sets c to 1 , b to c (or 1 ), and a to b (also 1 ).

a = b = c = 1

Thus, assignment is unusual in that it is right-associative.

Augmented assignment

Jython supports augmented assignment, which combines operators with assignment . The general form is v <op>= expression , which is equivalent to v = v <op> expression , except that v is evaluated only once (which can be important in a subscripted variable).

The following augmented assignment operators are available:

+= -= *= /= %= **= <<= >>= &= |= ^=

The if statement

The if , elif , and else statements provide basic decision capability. The test expressions evaluate to false (None, 0 or empty) or true (not-0 or not-empty).

This form is used to execute a statement or block conditionally:

if expression: statement -- or -- if expression: block

这是一个例子:

if x < 0: x = -x # ensure x is positive

The if-else statement

The following form is used to choose between two alternative statements and/or blocks:

if expression: statement else: statement -- or -- if expression: block else: block

这是一个例子:

if x >= 0: result = fac(x) else: print x, "is invalid for a factorial"

The if-elif-else statement

The following form is used to choose between a set of alternative statements and/or blocks:

if expression: statement elif expression: statement : else: statement -- or -- if expression: block elif expression: block : else: block

The elif clause can repeat. The else clause is optional. 这是一个例子:

if x == 0: doThis() elif x == 1: doThat() elif x == 2: doTheOtherThing() else: print x, "is invalid"

Conditional expressions

Most languages based on C, including C++ and the Java language, support a conditional expression . These expressions return a choice of sub-expressions. They are especially useful to avoid the use of repeated targets. This is important if the target contains complex expressions, such as subscripts. Conditional expressions have the form

=  ?  :

Jython does not support conditional expressions directly; instead it employs this form:

if expression: target = true_expression; else: target = false_expression -- or -- if expression: target = true_expression else: target = false_expression

You can approximate the Java conditional expression form in Jython using the and , and or operators, as shown here:

target = (expression) and (true_expression) or (false_expression)

Note that this form works only if true_expression and false_expression do not themselves evaluate to false values (such as None , 0, or an empty sequence or map). If that is the case, use the if-else form.

Implementing a switch statement

Jython does not support a switch or case statement like many other languages do. The if-elif-else form can be used to do similar tests for a limited number of cases. For more cases, you can use sequences or maps to functions (see Jython functions ), as follows:

: # define the function to handle each unique case def case1(...): return ... def case2(...): return ... : def caseN(...): return ... # defines cases in a dictionary; access by key cases = {key1:case1, key2:case2, ..., keyN:caseN} : result = cases[key](...) # get the selected case result -- or -- # defines cases in a list or tuple; access by index cases = (case1, case2, ..., caseN) : result = cases[x](...) # get the xth case result

The while statement

The while statement is used to perform conditional looping. As long as the expression evaluates to true the loop is executed. The while statement has the following forms:

while expression: statement else: statement -- or -- while expression: block else: block

The else clause, which is optional, is executed only if the while clause ends normally (that is, not with a break statement). It is not typically used.

例:

x = 10 while x > 0: process(x) x -= 1

The following is an infinite loop:

while 1: print "Hello!"

The for statement

The for statement is used to perform iterative looping. It processes a sequence returned from the supplied expression , taking each element in turn. As long as elements remain in the sequence, the loop is executed. The for statement has the following forms:

for vars in expression: statement else: statement -- or -- for vars in expression: block else: block

The else clause, which is optional, is executed only if the for clause ends normally (that is, not with a break statement). It is not typically used.

例:

for c in "String": processCharacter(c) # process the chars in turn -- or -- values = (1,2,5,7,9,-1) for v in values: process(v) # process the values supplied -- or -- for i in range(10): print i # print the values 0 to 9 on separate lines -- or -- for k, v in {"one":1, "two":2, "three":3}.items(): print k, '=', v # print the keys and values of a dictionary

In the above code, the use of for i in range(limit) provides for the typical for-loop or do-loop iteration of most languages. Note also that the keys will not necessarily come out in the order supplied.

The break and continue statements

It is sometimes necessary to exit a while or for loop in the middle. Often this is the result of some unusual condition that cannot be tested in the loop mechanism itself. The break statement provides this behavior. The statement has the following form:

break

这是一个例子:

for i in range(100): d = getData(i) if not valid(d): break # can't continue processData(d)

Likewise, it may be occasionally necessary to skip the rest of the loop body and begin the next iteration early. The continue statement provides this behavior. The statement has the following form:

continue

这是一个例子:

for i in range(100): : # *** some preliminary work *** if not valid(i): continue # can't process this one : # *** some other stuff ***

In general, the break and continue statements occur as the target of an if statement. Only the most closely contained loop can be controlled.

Updating a sequence

You must take special care when updating (that is, inserting or deleting entries from) a sequence while iterating over it, as this can cause the iteration indexes to change unpredictably. I recommend you make a copy of the sequence to iterate over, as shown below:

for i in x[:]: # iterate over a copy if i > 0: # remove all positive values x.remove(i)

The del statement

Mutable sequences (see Sequence types ), maps (see Maps and dictionaries ), and classes support the del statement, which removes an element or attribute from the collection or class, respectively. For sequences, removal is by index; for maps it is by key value; and for classes it is by attribute name. We'll talk more about class support for the del statement in Part 2 of this tutorial.

Local or global variables can be deleted; this removes the variable from the namespace (it does not delete the object the variable refers to). The del statement also supports the slice notation.

Assuming "l" is the list [1,2,3,4,5], d is the dictionary {1:"one", 2:"two", 3:"three"} and x is some class instance, some example del statements are as follows:

Comment(s)
del l[0] Removes the first element
del l[1:3] Removes the second through third elements
del l[::2] Removes the even elements
del l[:] Removes all the elements
del d[1] Removes the element with key 1
del x.attr1 Removes the attribute attr1
var = [1,2,3]
:
del var
Removes the variable var from its namespace

Jython functions

What are functions?

One of the most important features of any programming language is code reuse. There are two principle methods of code reuse: blocks of code that return values (called functions ) and blocks that do not return values (called subroutines ). Jython fully supports code reuse via functions.

Jython provides many built-in and library functions for you to use (see Appendix E: Built-in functions and Appendix F: Jython library summary ). Built-in functions can be used without importing them; library function must first be imported.

Jython goes beyond many languages, including the Java language, by making functions first-class objects that can be manipulated just like other objects (and most specifically, objects that can be stored in collections and passed as arguments to other functions).

The def statement

In Jython, functions are declared by the def statement, which has the following form:

def name ( args ): statement -- or -- def name ( args ): block

Within a given scope (module, function, or class), each function name should be unique. The function name is really a variable bound to the function body (similar to any other assignment). In fact, multiple variables can be defined to reference the same function. The function body can be a single (frequently a return) statement or (more commonly) a block of statements.

Specifying function arguments

The optional args in the def statement is a comma-separated list of argument definitions. Some examples follow:

Comment(s)
def x(a, b, c) Defines a function with three required positional arguments.
def x(a, b, c=1) Defines a function with three arguments, the last of which is optional with a default value of 1.
def x(a=3, b=2, c=1) Defines a function with three arguments, all of which are optional and have default values.
def x(p1, p2, kw1=1, kw2=2) Defines a function with two positional parameters and two keyword (optional) parameters. When declared, all optional (=value) parameters must follow all non-optional parameters. When this function is called, the keyword parameters, if provided, can be specified by name and in any order after positional parameters.
def x(p1, p2, *v) Defines a function with two required positional parameters and an indeterminate number of variable parameters. The v variable will be a tuple.
def x(p1, p2, **kw) Defines a function with two required positional parameters and an indeterminate number of keyword parameters. The kw variable will be a dictionary.
def x(p1, p2, *v, **kw) Defines a function with two required positional parameters and an indeterminate number of positional and keyword parameters. The v variable will be a tuple. The kw variable will be a dictionary.

Handling mutable arguments

If an argument accepts a default value of a mutable object (such as a list or dictionary) it's best to use the this form:

def x(p1, p2, p3=None) if p3 is None: p3 = [] :

rather than the simple one:

def x(p1, p2, p3=[]) :

Because the value after the equals sign is evaluated only when the function is defined (not each time it is called), the list in the second example above will be shared across all calls to the function. This is usually not the desired behavior. The first example gets a distinct list for each call.

Anonymous functions

You can define anonymous functions, called lambda functions. Anonymous functions are one-line functions that are typically used as arguments to other functions. These functions are declared using the following form:

lambda args: expression

The args list is the same as the one described in Specifying function arguments . You should have at least one argument per lambda function. The expression value is returned by the function.

The return statement

Functions return values via the return statement, which also exits a function. The return statement may or may not return an explicit value; if no value is specified, then None is used. If the last statement of a function body is not a return statement, then a value-less return is assumed. The return statement has the following forms:

return expression -- or -- return

Alternatively, this form lets you return multiple values as a tuple:

return expression1, expression2, ..., expressionN

Function calls

Functions are called by use of the call operator, which is a parenthesized list following a function reference. For example, if f is a function, then f(...) calls the function. If the function definition supports arguments, then the call may include parameters, as shown in the examples below:

Function definition Example call(s) Comment(s)
def x(a, b, c) x(1,2,3)
x("1", "2", "3")
Actual arguments can be of any type.
def x(a, b, c=1) x(1,2,3)
x(1,2)
Parameter c can be omitted
def x(a=3, b=2, c=1) x()
x(1,2,3)
x(c=10, a="d")
x(1,c=5)
Named parameters can be treated as positional, keyword, or mixed. If keyword, order is not important.
def x(p1, p2, kw1=1, kw2=2) x(1,2)
x(1,3,kw2=5)
Both positional and keyword parameters can be used.
def x(p1, p2, *v) x(1,2)
x(1,2,3)
x(1,2,3,4)
The v tuple gets the third and subsequent parameters.
def x(p1,p2,**kw) x(1,2, aaa=1, mmm=2, zzz=3) Keywords can have any name.
def x(p1,p2,*v, **kw) x(1,2,3,4, aaa=1, xxx="yyy") The v tuple gets the third and subsequent positional parameters while the dictionary kw gets the aaa and xxx keys with values.

Note that spaces are optional between parameter declarations and arguments. Adding a space between each is recommended for increased readability.

Example function definitions and calls

Below are some example function definitions with example calls.

def k(): return 1 # return the constant 1 print k() # prints 1 # below replaces the built-in abs definition def abs(x): # calc the absolute value if x < 0: return -x return x print abs(-10) # prints 10 sum = lambda x, y: x + y # define sum function print sum(1,2) # prints 3 prod = lambda x, y: x * y # define prod function print prod(1,2) # prints 2 # fully equivalent to the above, # but the above binding of prod is replaced def prod(x, y): return x * y # define the prod function print prod(1,2) # prints 2 # make an alias of prod xy = prod print xy(1,2) # prints 2 # a function that takes a function # similar to the built-in function apply def applyer (func, args): return func(*args) print applyer(xy, (1,2)) # prints 2 print applyer(lambda x,y: x ** y, (2,16)) # prints 65536 def factorial(x): "calculate the factorial of a number" if x < 0: raise ValueError, "negative factorial not supported" if x < 2: return 1 return long(x) * factorial(x-1) print factorial(3) # prints 6

The global statement

Occasionally, you may want to declare (that is, assign to) a variable in a local context (such as in a function) but reference a variable in the global scope. To do this, use the global statement before the first use of the variable. 这是一个例子:

x = 10; y = 20; z = 30 # three global variables def f1(p, q, r): x = p # local x, y & z variables y = q z = r def f2(a, b, c): global x, y x = a # global x & y variables y = b z = c # local z variable print x, y, z # prints: 10, 20, 30 f1(1, 2, 3) print x, y, z # prints: 10, 20, 30 f2(-1, -2, -3) print x, y, z # prints: -1, -2, 30

Note that as long as it is not re-bound locally, a global variable can be read without first declaring it to be a global. Thus the global statement is only required to assign to a global variable.

Generic functions

Similar to in Smalltalk functions, Jython functions are generic in that any type can be passed in for each argument. This makes functions extremely flexible. Generic functions work as long as the operations performed on the arguments in the function are valid for the argument's actual type. For example, with these functions' definitions

def sum (x, y): return x + y def prod (x, y): return x * y

the following function calls are valid:

print sum(1, 2) # prints 3 print sum('123', '456') # prints 123456 print sum([1,2,3], [4,5,6]) # prints [1,2,3,4,5,6] print prod(2, 3) # prints 6 print prod('123', 2) # prints 123123

Dynamic type testing

You can use dynamic type testing (that is, using the isinstance function or comparing the results of the type function) for even more flexibility. See Appendix G: Jython types summary for more information. 这是一个例子:

# See Part 2 of this tutorial for the definition of the UserList class from UserList import * : data = None # undefined until setData called prevdata = [] def setData (values=None): """ Set global data. """ global data, prevdata # use the global data if not data is None: # save any prior versions prevdata.append(data) data = [] # create default empty data space if not values is None: # some initial values supplied if isinstance(values, UserList): # values is a UserList data = values.data[:] # set to copy of UserList's values else: # values is some other sequence # this will fail if values is not some form of sequence data = list(values) # convert to a list : print data # prints None : setData("123456") print data # prints ['1',2','3','4','5','6'] : setData((1,2,3,4,5,6)) print data # prints [1,2,3,4,5,6] : xdata = data[:]; xdata.reverse() setData(xdata) print data # prints [6,5,4,3,2,1] : print prevdata # prints [['1',2','3','4','5','6'],[1,2,3,4,5,6]]

Nested functions

Unlike many other languages, including the Java language, Jython allows functions to be defined inside of other functions. The nested (or local ) functions can help to reduce the scope of functions. 这是一个例子:

def x(a, b, c): y = a * b def square(x): return x ** 2 # this x is different from function x y *= square(c) return x

The nested function has no visibility into the variables in the containing function. If the nested function must use these values, pass them into the function as arguments. For example, the following function

def calc(a, b, c): x = a * b * c def sum(data): # cannot access calc's namespace (x, a, b, c, or sum) here print locals() return data['a'] + data['b'] + data['c'] x += sum(locals()) return x print calc(10,20,30)

版画

{'data': {'x': 6000, 'c': 30, 'b': 20, 'sum': \ <function sum at 32308441>, 'a': 10}} 6060

Nested functions can also be used to conveniently create (preconfigured) functions to return as a result, as shown here:

def makeSq(n): def sq(x=n): # n's value is saved as the parameter x value return x ** 2 return sq

The above function can be used like this:

sq2 = makeSq(2) print "2*2=%i" % sq2() # prints: 2*2=4 sq10 = makeSq(10) print "10*10=%i" % sq10() # prints: 10*10=100

Functional programming

Like Lisp and Smalltalk, Jython supports a limited form of functional programming. Functional programming uses the first-class nature of Jython functions and performs operations on functions and data structures. The built-in functional programming services are shown below:

Syntax Use/Comment(s) Example(s)
apply(func, pargs {, kargs})
func(*pargs {, **kargs})
Execute the function with the supplied positional arguments and optional keyword arguments. apply(lambda x, y: x*y, (10, 20)) --> 200
map(func, list, ...) Creates a new list from the results of applying func to each element of each list. There must be one list per argument to the function. map(lambda x, y: x+y, [1,2],[3,4]) --> [4,6]
map(None, [1,2],[3,4]) --> [[1,3],[2,4]]
reduce(func, list {,init}) Applies func to each pair of items in turn. The results are accumulated. reduce(lambda x, y: x+y, [1,2,3,4],5) --> 15
reduce(lambda x, y: x&y, [1,0,1]) --> 0
reduce(None, [], 1) --> 1
filter(func, seq) Creates a new list from seq selecting the items for which func returns true . func is a one-argument function. filter(lambda x: x>0, [1,-1,2,0,3]) --> [1,2,3]

Using functions like map , reduce , and filter can make processing sequences (that is, strings, lists, and tuples) much easier. These functions are higher-order functions because they either take functions as arguments or return them as results.

Functional programming examples

We'll close this section on Jython functions, and the first half of the "Introduction to Jython" tutorial, with some functional programming examples.

A factorial calculator can be implemented using reduce :

def fac(x): return reduce(lambda m,n: long(m)*n, range(1,x)) print fac(10) # prints 362880L

List modification can be done using map :

l = [1, -2, 7, -3, 0, -11] l = map(abs, l) print l # prints [1, 2, 7, 3, 0, 11]

A set of functions can be executed in a sequence using map :

def f1(x): return ... def f2(x): return ... def f3(x): return ... : def fM(x): return ... : def fN(x): return ... # x=(5) is an example of a parameter for each function, # any expression is allowed, each function will get it # the list determines the order of the functions # the result of each function is returned in a list. results = map(lambda f,x=(5): f(x), [fN,f3,f2,f3,...,fM,...,f1])

Looping can be achieved using map :

def body1(count): # any body here : # do body 10 times, passing the loop count map(body1, range(10)) def body2(x,y,z): # any body here : # do body with multiple parameters # calls body2(1, 'a', "xxx") # then body2(2, 'b', "yyy") # then body2(3, 'c', "zzz") map(body2, [1,2,3], "abc", ["xxx", "yyy", "zzz"])

Selection can be achieved using filter :

# Assume a class Employee exists with attributes # name, age, sex, title, spouse and children (among others) # and that instances such as John, Mary and Jose exist. # See Part 2 of this tutorial for more information on using classes. John = Employee('John', 35, 'm', title='Sr. Engineer') Mary = Employee('Mary', 22, 'f', title='Staff Programmer') Jose = Employee('Jose', 50, 'm', title='Dept. Manager', children=[...]) employees = [John, Jose, Mary]

Here's an example of how we'd use the above filter to select some employees:

# returns: [Jose] hasChildren = filter(lambda e: e.children, employees) # returns: [] over65 = filter(lambda e: e.age>65, employees) # returns: [Mary] isProgrammer = filter(lambda e: \ e.title and e.title.lower().find('prog') >= 0, employees)

Wrapping up

摘要

In this first half of the two-part "Introduction to Jython" tutorial, you've learned the concepts and programming basics of working with Jython, including access options and file compilation, syntax and data types, program structure, procedural statements, and functional programming with Jython.

In the second half of this tutorial, we will begin to wrestle with some of the more advanced aspects of the language, starting with a conceptual and hands-on introduction to object-oriented programming in Jython. You'll also learn about debugging, string processing, file I/O, and Java support in Jython. The tutorial will conclude with an exciting, hands-on demonstration of how to build a working GUI app in Jython.

It's a good idea to take the second part of the tutorial as soon as you can, while the concepts from Part 1 are still fresh in your mind. If you prefer to take a break in your studies, you might want to use the time to explore the appendices included with Part 1 ( Appendices ), or check out some of the references included in the Related topics section.

附录

Appendix A: Escape characters

Several special characters have backslash versions:

Backslash Representation 字符
\t 标签
\v Vertical-Tab
\n New-Line
\r 返回
\f Form-Feed
\" 引用
\' 使徒
\\ Backslash
\b 退格键
\a
\000 Octal value (3 base-8 digits in range 0-377 8 )
\xXX... Hex value (2 base 16-digits in range 0-FF 16 ) used in strings (that is, "\x31" --> '1')
\uXXXX... Hex value (4 base 16-digits in range 0-FFFF 16 ); used in unicode strings (that is, u"\u0031" --> '1')

Appendix B: String methods

Strings support several useful methods:

方法 用法
s.capitalize() Initial capitalize s "abc".capitalize() --> "Abc"
s.count(ss {,start {,end}}) Count the occurrences of ss in s[start:end] "aaabbccc".count("ab") --> 1个
s.startswith(str {, start {, end}})
s.endswith(str {, start {, end}})
Test to see if s starts/ends with str "xxxyyyzzz".startswith("xx") --> 1个
s.expandtabs({size}) Replace tabs with spaces, default size: 8 "x\ty".expandtabs(4) --> "xy"
s.find(str {, start {, end}})
s.rfind(str {, start {, end}})
Finds first index of str in s; if not found: -1, rfind searches right-to-left "12345".find('23') --> 1个
s.index(str {, start {, end}})
s.rindex(str {, start {, end}})
Finds first index of str in s; if not found: raise ValueError. rindex searches right-to-left "12345".index('23') --> 1个
s.isalnum Test to see if the string is alphanumeric "12345abc".isalnum() --> 1个
s.isalpha Test to see if the string is alphabetic "12345abc".isalpha() --> 0
s.isnum Test to see if the string is numeric "12345abc".isnum() --> 0
s.isupper Test to see if the string is all uppercase "abc".isupper() --> 0
s.islower Test to see if the string is all lowercase "abc".islower() --> 1个
s.isspace Test to see if the string is all whitespace "12345 abc".isspace() --> 0
s.istitle Test to see if the string is a sequence of initial cap alphanumeric strings "Abc Pqr".istitle() --> 1个
s.lower()
s.upper()
s.swapcase()
s.title()
Convert to all lower, upper, opposite, or title case "abcXYZ".lower() --> "abcxyz"
"abc def ghi".title() --> "Abc Def Ghi"
s.join(seq) Join the strings in seq with s as the separator " ".join(("hello", "goodbye") --> "hello goodbye"
s.splitlines({keep}) Split s into lines, if keep true, keep the newlines "one\ntwo\nthree".splitlines() --> ["one", "two", "three"]
s.split({sep {, max}}) Split s into "words" using sep (default of white space) for up to max times "one two three".split() --> ["one", "two", "three"]
s.ljust(width)
s.rjust(width)
s.center(width)
s.zfill(width)
Left, right or center justify the string in a field width wide. Fill with 0. "xxx".rjust(8) --> " xxx"
"xxx".center(8) --> " xxx "
str(10).zfill(10) --> "0000000010"
s.lstrip()
s.rstrip()
s.strip()
Remove leading (and/or trailing) white space " xxx ".strip() --> "xxx"
s.translate(str {,delc}) Translate s using table, after removing any characters in delc. str should be a string with length == 256 "ab12c".translate(reversealpha, "0123456789") --> "cba"
s.replace(old, new {, max}) Replaces all or max occurrences old string old with string new "11111".replace('1', 'a', 2) --> "aa111"

Note: other methods are supported, for a complete list see the Python Library Reference ( Related topics ). Also note that by including the string module, many (but not all) of these methods can also be called as functions, ie- string.center(s, 10) is the same as s.center(10) .

The string module has some important variables:

Variable Comment(s)
数字
octdigits
hexdigits
The decimal, octal, and hexadecimal digits
lowercase
uppercase
letters
The lowercase alphabet, the uppercase alphabet, and the union of them
whitespace The legal white space characters

Appendix C: List methods

Lists support several useful methods.

功能 Comment(s)
x in l
x not in l
Test for containment 1 in [1,2,3,4] --> 1个
l.count(x) Count the occurrences of x. Uses "==" to test. [1,2,3,3].count(3) --> 2
l.append(x)
-- or --
l = l + [x]
Append x to the list [1,2].append([3,4]) --> [1,2,[3,4]]
[1,2] + [3] --> [1,2,3]
l.extend(list) Appends the elements of list [1,2].extend([3,4]) --> [1,2,3,4]
l.index(item) Finds the index of item in list; if not present, raise ValueError [1,2,3,4].index(3) --> 2
l.insert(index, x)
-- or --
l[i:i] = [x]
Insert x into the list before the index [1,2,3].insert(1, 4) --> [1,4,2,3]
l.pop({index}) Removes the nth (default last) item [1,2,3,4].pop(0) --> [2,3,4], 1
[1,2,3,4].pop() --> [1,2,3], 4
l.remove(x) Removes the item from the list [1,2,3,4].remove(3) --> [1,2,4]
l.reverse() Reverses the list (in-place) [1,2,3].reverse() --> [3,2,1]
l.sort({cmp}) Sorts the list (in-place); The cmp function is used to sort the items. The cmp function takes two argument and returns <0, 0, >0 [1,4,3,2].sort() --> [1,2,3,4]

Appendix D: Map methods

Maps support several useful methods.

方法 Comment(s)
m.clear() Empty the map
m.copy() Make a shallow copy of the map
m.has_key(k)
-- or --
k in m
Test to see if a key is present
m.items() Get a list of the key/value tuples
m.keys() Get a list of the keys
m.values() Get a list of the values (may have duplicates)
m1.update(m2) add all the items in m2 to m1
m.get(k{, default})
m.setdefault(k, default)
Get the value of k, return default/KeyError if missing; same as get, but set a persistent default value
m.popitem() Get and remove some item, used during iteration over the map. 例:

m = {1:1, 2:2, 3:3} while len(m) > 0: i = m.popitem() print i

Appendix E: Built-in functions

Jython provides very useful built-in functions that can be used without any imports. The most commonly used ones are summarized below:

Syntax Use/Comment(s) Example(s)
绝对(x) Absolute value abs(-1) --> 1个
apply(func, pargs {, kargs})
-- or --
func(*pargs {, **kargs})
Execute the function with the supplied positional arguments and optional keyword arguments apply(lambda x, y: x * y, (10, 20)) --> 200
callable(x) Tests to see if the object is callable (ie, is a function, class or implements __call__) callable(MyClass) --> 1个
chr(x) Converts the integer (0 - 65535) to a 1-character string chr(9) --> "\t"
cmp(x, y) Compares x to y: returns: negative if x < y; 0 if x == y; positive if x > ÿ cmp("Hello", "Goodbye") --> > 0
coerce(x, y) Returns the tuple of x and y coerced to a common type coerce(-1, 10.2) --> (-1.0, 10.2)
compile(text, name, kind) Compile the text string from the source name. Kind is: "exec", "eval" or "single"
x = 2 c = compile("x * 2", "<string>", "eval") eval(c) --> 4
complex(r, i) Create a complex number complex(1, 2) --> 1.0+2.0j
complex("1.0-0.1j") --> 1.0-0.1j
dir({namespace}) Returns a list of the keys in a namespace (local if omitted) dir() --> [n1, ..., nN]
vars({namespace}) Returns the namespace (local if omitted); do not change it vars() --> {n1:v1, ..., nN:vN}
divmod(x, y) Returns the tuple (x /y, x % y) divmod(100, 33) --> (3, 1)
eval(expr {, globals {, locals}}) Evaluate the expression in the supplied namespaces
myvalues = {'x':1, 'y':2} eval("x + y", myvalues) --> 3
execfile(name {,globals {, locals}}) Read and execute the named file in the supplied namespaces execfile("myfile.py")
filter(func, list) Creates a list of items for which func returns true filter(lambda x: x > 0, [-1, 0, 1, -5, 10]) --> [1, 10]
float(x) Converts x to a float float(10) --> 10.0
float("10.3") --> 10.3
getattr(object, name {, default}) Gets the value of the object's attribute; if not defined return default (or an exception if no default) getattr(myObj, "size", 0) --> 0
setattr(object, name, value) Creates/sets the value of the object's attribute setattr(myObj, "size", 10)
hasattr(object, name) Test to see if the object has an attribute hasattr(myObj, "size") --> 0
globals() Returns the current global namespace dictionary {n1:v1, ..., nN:vN}
locals() Returns the current local namespace dictionary {n1:v1, ..., nN:vN}
hash(object) Returns the object's hash value. Similar to java.lang.Object.hashCode() hash(x) --> 10030939
hex(x) Returns a hex string of x hex(-2) --> "FFFFFFFE"
id(object) Returns a unique stable integer id for the object id(myObj) --> 39839888
input(prompt) Prompts and evaluates the supplied input expression; equivalent to eval(raw_input(prompt)) input("Enter expression:")
with "1 + 2" --> 3
raw_input(prompt) Prompts for and inputs a string raw_input("Enter value:")
with "1 + 2" --> "1 + 2"
int(x{, radix}) Converts to an integer; radix: 0, 2..36; 0 implies guess int(10.2) --> 10
int("10") --> 10
int("1ff", 16) --> 511
isinstance(object, class) Tests to see if object is an instance of class or a subclass of class; class may be a tuple of classes to test multiple types isinstance(myObj, MyObject) --> 0
isinstance(x, (Class1, Class2)) --> 1个
issubclass(xclass, clsss) Tests to see if xclass is a sub-(or same) class of class; class may be a tuple of classes to test multiple types issubclass(MyObject, (Class1, Class2)) --> 0
len(x) Returns the length (number of items) in the sequence or map len("Hello") --> 5
list(seq) Converts the sequence into a list list((1, 2, 3)) --> [1,2,3]
list("Hello") --> ['H','e','l','l','o']
tuple(seq) Converts the sequence into a tuple tuple((1, 2, 3)) --> (1,2,3) tuple("Hello")--> ('H','e','l','l','o')
long(x {, radix}) Converts to a long integer; radix: 0, 2..36; 0 implies guess long(10) --> 10L
long("10000000000") -->
10000000000L
map(func, list, ...) Creates a new list from the results of applying func to each element of each list map(lambda x,y: x+y, [1,2],[3,4]) --> [4,6]
map(None, [1,2],[3,4]) --> [[1,3],[2,4]]
max(x) Returns the maximum value max(1,2,3) --> 3
max([1,2,3]) --> 3
min(x) Returns the minimum value min(1,2,3) --> 1个
min([1,2,3]) --> 1个
oct(x) Converts to an octal string oct(10) --> "012
oct(-1) --> "037777777777"
open(name, mode {, bufsize}) Returns an open file. Mode is:(r|w|a){+}{b} open("useful.dat", "wb", 2048)
ord(x) Returns the integer value of the character ord('\t') --> 9
pow(x,y)
pow(x,y,z)
Computes x ** y
Computes x ** y % z
pow(2,3) --> 8
range({start,} stop {, inc})
xrange({start,} stop {, inc})
Returns a sequence ranging from start to stop in steps of inc; start defaults to 0; inc defaults to 1. Use xrange for large sequences (say more than 20 items) range(10) --> [0,1,2,3,4,5,6,7,8,9]
range(9,-1,-1) --> [9,8,7,6,5,4,3,2,1,0]
reduce(func, list {, init}) Applies func to each pair of items in turn accumulating a result reduce(lambda x,y:x+y, [1,2,3,4],5) --> 15
reduce(lambda x,y:x&y, [1,0,1]) --> 0
reduce(None, [], 1) --> 1个
repr(object)
-- or --
`object`
Convert to a string from which it can be recreated, if possible repr(10 * 2) --> "20"
repr('xxx') --> "'xxx'"
x = 10; `x` --> "10'"
round(x {, digits}) Rounds the number round(10.009, 2) --> 10.01
round(1.5) --> 2
str(object) Converts to human-friendly string str(10 * 2) --> "20"
str('xxx') --> 'xxx'
type(object) Returns the type (not the same as class) of the object. To get the class use object.__class__ . Module types has symbolic names for all Jython types x = "1"; type(x) is type('') --> 1个
zip(seq, ...) Zips sequences together; results is only as long as the shortest input sequence zip([1,2,3],"abc") --> [(1,'a'),(2,'b'),(3,'c')]

See the Python Library Reference ( Related topics ) for more details.

Appendix F: Jython library summary

Jython supports a large number of Python libraries. By using only these libraries it is possible to write Jython programs that will work in any Python environment. Many of these libraries provide similar function to those provided by the Java APIs. Jython also has access to all Java libraries. This means it can do anything a Java program can do but then it is no longer possible to run the program in a Python environment.

Most libraries that are written in Python and do not depend on operating system specific services are supported without change. Many of these libraries are shipped with Jtyhon. Libraries written in C must be converted; many of the core C libraries have been converted and are shipped with Jython.

Jython also has a few unique libraries of its own. These libraries supplement the extensive API libraries provided by Java itself. For more details on these libraries, read the source files (in <jython_install_dir>/Lib/<lib_name>.py) or see the Python Library Reference ( Related topics ).

Some of the more interesting external libraries supplied with Jython include:

图书馆 Comment (often from the library prolog)
atexit Allows a programmer to define multiple exit functions to be executed upon normal program termination
base64 Conversions to/from base64 transport encoding as per RFC-1521
BaseHTTPServer HTTP server base class (abstract)
bdb Generic Python debugger base class
bisect Some Bisection algorithms
日历 Calendar printing functions (in English)
cgi Support module for CGI (Common Gateway Interface) scripts
CGIHTTPServer CGI-savvy SimpleHTTPServer
命令 A generic class to build line-oriented command interpreters
Utilities needed to emulate Python's interactive interpreter
codecs Python Codec Registry, API and helpers (abstract)
colorsys Conversion functions between RGB and other color systems
ConfigParser Configuration file parser
曲奇饼 Cookie is a module for the handling of HTTP cookies as a dictionary
复制 Generic (shallow and deep) copying operations
difflib Utilities for computing deltas between objects
dircache Read and cache directory listings
doctest A framework for running examples in document strings (sort of like JUnit); I recommend unittest below
dumbdbm A dumb and slow but simple dbm clone
fileinput Class to quickly write a loop over all standard input files
fnmatch Filename matching with shell patterns
格式化程序 Generic output formatting framework (abstract)
fpformat General floating point formatting functions
ftplib An FTP client class and some helper functions
getopt Parser for command line options (UNIX style)
glob Filename globbing (a list of paths matching a pathname pattern) utility
gopherlib Gopher protocol client interface
gzip Functions that read and write gzipped files
htmlentitydefs HTML character entity references
httplib HTTP/1.1 client library
imaplib IMAP4 client
imghdr Recognize selected image file formats based on their first few bytes
isql Provides an interactive environment for database work
linecache Cache lines from files
mailcap Mailcap file handling. See RFC 1524
mimetools Various tools used by MIME-reading or MIME-writing programs
mimetypes Guess the MIME type of a file
MimeWriter Generic MIME writer
mimify Mimification and unmimification of mail messages
multifile A readline()-style interface to the parts of a multipart message
nntplib An NNTP client class based on RFC 977: Network News Transfer Protocol
nturl2path Convert a NT pathname to a file URL and vice versa
pdb A Python debugger
泡菜 Create portable serialized representations of Jython (not Java) objects
管道 Conversion pipeline templates
poplib A POP3 client class
posixfile Extended file operations available in POSIX
pprint Support to pretty-print lists, tuples, & dictionaries recursively
个人资料 Class for profiling python code
pstats Class for printing reports on profiled python code
pyclbr Parse a Python file and retrieve classes and methods
队列 A multi-producer, multi-consumer queue
quopri Conversions to/from quoted-printable transport encoding as per RFC-1521
随机 Random variable generators
回覆 Regular Expression Engine (clone of sre)
代表 Redo the '...' (representation) but with limits on most sizes
rfc822 RFC-822 message manipulation class
预定 A generally useful event scheduler class
sgmllib A SAX-like parser for SGML (subset as used by HTML), using the derived class as a static DTD (abstract)
shelve Manage shelves (persistent, dictionary) of pickled objects
shutil Utility functions for copying files and directory trees
SimpleHTTPServer A Simple HTTP Server (text HEAD and GET only)
smtplib SMTP/ESMTP client class that follows RFC-821 (SMTP) and RFC-1869 (ESMTP)
sndhdr Routines to help recognizing select sound files
socket Basic socket support
SocketServer Generic socket server classes
sre Regular Expression Engine
统计 Constants/functions for interpreting results of os.stat() and os.lstat()
Common string manipulations; a (very useful) collection of string operations. The string type also supports most of these functions as methods.
StringIO File-like object that reads from or writes to a string buffer
telnetlib TELNET client class based on RFC-854
tempfile Temporary files and filenames
threading New threading module, emulating a subset of the Java platform's threading model
tokenize Tokenization help for Python programs
traceback Extract, format and print information about Python stack traces
单元测试 Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework
urllib Open an arbitrary URL
urlparse Parse (absolute and relative) URLs
用户 Hook to allow user-specified customization code to run at start-up
UserDict A more or less complete user-defined wrapper around dictionary objects
UserList A more or less complete user-defined wrapper around list objects
UserString A user-defined wrapper around string objects
whrandom Wichman-Hill random number generator
xmllib A SA-like parser for XML, using the derived class as static DTD (abstract)
zipfile Read and write ZIP files
__future__ Used to access features from future versions that are available (potentially in less than finished form) today

Note: I do not claim the above library modules work or are error free on Jython, especially when you are not running on a UNIX system. Try them interactively before you decide to code to them.

Appendix G: Jython types summary

Jython supports many object types. The module types defines symbols for these types. The function type gets the type of any object. The type value can be tested (see Dynamic type testing ). The table below summarizes the most often used types.

Type symbol Jython runtime type Comment(s)
ArrayType PyArray Any array object
BuiltinFunctionType PyReflectedFunction Any built-in function object
BuiltinMethodType PyMethod Any built-in method object
ClassType PyClass Any Jython class object
ComplexType PyComplex Any complex object
DictType
-- or --
DictionaryType
PyDictionary Any dictionary object
FileType PyFile Any file object
FloatType PyFloat Any float object
FunctionType PyFunction Any function object
InstanceType PyInstance Any class instance object
-- none -- PyJavaInstance Any Java class instance object
IntType PyInteger Any integer object
LambdaType PyFunction Any lambda function expression object
ListType PyList Any list object
LongType PyLong Any long object
MethodType PyMethod Any non-built-in method object
ModuleType PyModule Any module object
NoneType PyNone Any None (only one) object
StringType PyString Any ASCII string object
TracebackType PyTraceback Any exception traceback object
TupleType PyTuple Any tuple object
类型类型 PyJavaClass Any type object
UnboundMethodType PyMethod Any method (without a bound instancee) object
UnicodeType PyString Any Unicode string object
XRangeType PyXRange Any extended range object

Note: several types map to the same Java runtime type.

For more information on types see the Python Library Reference ( Related topics ).

Appendix H: Format codes

The format operator (see Formatting strings and values supports the following format characters:

Character(s) Result Format Comment(s)
%s, %r %s does str(x) , %r does repr(x)
%i, %d Integer Decimal Basically the same format
%o, %u, %x, %X Unsigned Value In octal, unsigned decimal, hexadecimal
%f, %F Floating Decimal Shows fraction after decimal point
%e, %E, %g, %G Exponential %g is %f unless the value is small; else %e
%c 字符 Must be a single character or integer
%% 字符 The % character

Note: more details on the structure and options of the format item can be found in the Python Library Reference ( Related topics ). Use of case in format characters (for example, X vs x causes the symbol to show in matching case.


翻译自: https://www.ibm.com/developerworks/java/tutorials/j-jython1/j-jython1.html

jython 调用java_Jython简介,第1部分:Java编程变得更容易相关推荐

  1. java会变得更简单吗_spring 第一篇(1-1):让java开发变得更简单(下)

    切面(aspects)应用 DI能够让你的软件组件间保持松耦合,而面向切面编程(AOP)能够让你捕获到在整个应用中可重用的组件功能.在软件系统中,AOP通常被定义为提升关注点分离的一个技术.系统由很多 ...

  2. UC浏览器设置代理服务器JAVA_uc浏览器让JAVA手机变“聪明”的方法

    摘要: 智能手机之所以聪明,主要是因为它能够同时进行多项操作是因为其借助了后台运行,所谓的后台运行,也就是将运行程序界面最小化,就像在电脑上的操作一样,同时打开多个程序状态下,进行一项操作,其他的程序 ...

  3. jwt 例子 java_spring boot 入门之security oauth2 jwt完美整合例子-java编程

    一.本文简介 本文主要讲解Java编程中spring boot框架+spring security框架+spring security oauth2框架整合的例子,并且oauth2整合使用jwt方式存 ...

  4. java编程学习必备好书-蛙课网

    对于学习java编程的同学来说,一本好书,可以让你沉浸java的知识海洋中.如果java零基础想要入门,那么看什么样的书籍比较适合呢,怎么才能从轻松入门到深入学习呢?下面我给大家介绍一些java编程书 ...

  5. Jython 调用 Java 碰壁全纪录

    JavaClass 的定义 public class JavaClass {     private String str = "";     public JavaClass() ...

  6. java 调用python脚本过程_通过Java调用Python脚本

    在进行开发的过程中,偶尔会遇到需要使用Java调用Python脚本的时候,毕竟Python在诸如爬虫,以及科学计算等方面具有天然的优势.最近在工作中遇到需要在Java程序中调用已经写好的Python程 ...

  7. Jython调用不包含第三方库的python脚本

    1.本地环境安装的是Python 2.7.11 2.用maven下载jython依赖 <pre name="code" class="html">& ...

  8. java程序设计专业介绍_简介Java编程中的Object类

    这篇文章主要介绍了简介Java编程中的Object类,是Java入门学习中的基础知识,需要的朋友可以参考下 Object 类位于 java.lang 包中,是所有 Java 类的祖先,Java 中的每 ...

  9. ECshop在文章列表页调用文章简介

    1.打开includes/lib_article.php文件: 找到:大约21行-82行代码,替换为一下 /** * 获得文章分类下的文章列表 * * @access public * @param ...

最新文章

  1. 为什么在MM32中的MicroPython中无法打开二进制文件呢?
  2. C#上位机软件串口数据接收用Invoke(同步)和BeginInvoke(异步)的区别
  3. html的input的id,请求[“inputId”]不能在cshtml上工作
  4. FlexChart: 针对AJAX的Flash绘图应用
  5. 会话跟踪之Session
  6. c++ 线程间通信方式
  7. 麦子学院python百度云_麦子学院python
  8. opencv摄像头捕获视频
  9. JAVA项目在服务器部署过程
  10. java天猫精灵_教你玩转天猫精灵:把设备接入天猫精灵
  11. 抓网页_面包网_javaSE
  12. sql 修改时间正价 2天_“熬夜3天,修改17遍,我终于写出了1篇稿费2万的稿子”...
  13. 讲讲自己试用期被劝退的经历!
  14. 学信网学位认证报告在哪
  15. 【LeetCode每日一题】——714.买卖股票的最佳时机含手续费
  16. 实现网上购物系统的后台管理(增、删、改、查图书)。
  17. Excel根据表格内容批量导入指定图片到单元格
  18. 探索鼎龙湾德萨斯牛仔小镇,欣赏粤西非遗文化的魅力
  19. 118 Servlet_1 _Tomcat服务器
  20. C++设计:关于CMatrix类的相关操作

热门文章

  1. python对比两张图片找不同
  2. 圆形标定板的图像校正
  3. 浅谈游戏《艾迪芬奇的记忆》
  4. 16秋计算机与技术鲁嘉华第一章作业
  5. openlayers6【二十二】vue addLayer实现点击地图添加图标要素信息,编辑点位信息
  6. Vue使用Echarts实现数据可视化
  7. Java 实现分布式定时任务
  8. 你遇到过开机没反应的现像吗?
  9. 数据加密 第五篇:非对称密钥
  10. 67.220.90.12/bbs/index.php,对乌云漏洞库的分析.md