97、Jython 内置函数与语句快速参考

Jython 内置函数与语句快速参考

1. 内置函数概述

Jython 提供了丰富的内置函数,这些函数可以帮助开发者更高效地完成各种任务。下面将详细介绍一些常用的内置函数。

1.1 部分内置函数介绍

函数 描述 语法 示例
abs 返回数字的绝对值 abs(number) >>> abs(-5.43)
5.43
apply 调用对象 apply(object[, args[, kwargs]]) python<br>>>> def printKWArgs(**kw):<br>... print kw<br>...<br>>>> apply(printKWArgs, (), globals())<br>
callable 判断对象是否可调用 callable(object) python<br>>>> def myFunction():<br>... return<br>...<br>>>> callable(myFunction)<br>1<br>>>> callable("a string")<br>0<br>
chr 对于小于等于 65535 的整数,返回具有指定整数值的字符 chr(integer) python<br>>>> chr(119)<br>'w'<br>>>> chr(88)<br>'X'<br>>>> chr(50000)<br>u'\uC350'<br>
cmp 比较两个参数,根据大小关系返回 -1、0 或 1 cmp(x, y) python<br>>>> cmp(1, 3)<br>-1<br>>>> cmp(3, 1)<br>1<br>>>> cmp(3, 3)<br>0<br>
coerce 测试两个对象是否有共同类型,有则返回同类型对象的元组,否则抛出 TypeError coerce(x, y) python<br>>>> coerce(3.1415, 6) # float and int<br>(3.1415, 6.0)<br>>>> results = coerce("a", 2.3)<br>Traceback (most recent call last):<br> File "<stdin>", line 1, in ?<br>TypeError: number coercion failed<br>
compile 将字符串编译为代码对象 compile(source, filename, mode) python<br>>>> co = compile("0 and 'This' or 1 and 'that'", "-", "eval")<br>>>> exec(co)<br>>>> eval(co)<br>'that'<br>>>> co = compile("for x in range(10):\n\tprint x, ", "<console>", "single")<br>>>> exec(co)<br>0 1 2 3 4 5 6 7 8 9<br>

1.2 内置函数调用流程

graph TD;
    A[选择函数] --> B{函数类型};
    B -- 数值处理 --> C[调用 abs、cmp 等函数];
    B -- 对象操作 --> D[调用 callable、delattr 等函数];
    B -- 字符串处理 --> E[调用 chr、ord 等函数];
    B -- 代码处理 --> F[调用 compile、eval 等函数];

2. 语句使用说明

Jython 中的语句用于控制程序的流程和结构。以下是一些常见语句的详细介绍。

2.1 部分语句介绍

语句 描述 语法 示例
assert 测试表达式是否为真,否则抛出异常 "assert" expression [, expression] python<br>>>> a = 21<br>>>> assert a < 10<br>Traceback (innermost last):<br> File "<console>", line 1, in ?<br>AssertionError:<br>
break 终止内层循环并继续执行循环块后的代码 "break" python<br>>>> for x in (1, 2, 3, 4):<br>... if x == 3:<br>... break<br>... print x<br>...<br>1<br>2<br>
class 开始类的定义 "class" name[(base-class-name(s))]: python<br>>>> class test: # no base class<br>... pass # place holder<br>...<br>>>> t = test() # Calls class to create an instance<br>
continue 暂停当前循环块的执行,开始下一次迭代 "continue" python<br>>>> for x in (1, 2, 3, 4):<br>... if x == 3:<br>... continue<br>... print x<br>...<br>1<br>2<br>4<br>
def 开始函数或方法的定义 "def" name(([parameters]): code-block python<br>>>> def caseless_srch_n_replace(string, srch, rplc):<br>... return string.lower().replace(srch, rplc)<br>...<br>>>> S = "Some UseLess text"<br>>>> caseless_srch_n_replace(S, "useless", "useful")<br>'some useful text'<br>
del 从命名空间中移除变量 "del" identifier python<br>>>> a = "foo"<br>>>> print a<br>foo<br>>>> del a<br>>>> print a<br>Traceback (innermost last):<br> File "<console>", line 1, in ?<br>NameError: a<br>

2.2 语句执行流程

graph TD;
    A[程序开始] --> B{遇到语句类型};
    B -- 条件判断 --> C[执行 if、elif、else 语句];
    B -- 循环控制 --> D[执行 for、while 语句];
    B -- 异常处理 --> E[执行 try/except 语句];
    B -- 函数与类定义 --> F[执行 def、class 语句];
    B -- 变量操作 --> G[执行 del、global 语句];

3. 操作示例

3.1 内置函数操作步骤

  • 使用 abs 函数获取绝对值
    1. 定义一个数字变量,例如 num = -10
    2. 调用 abs 函数, result = abs(num)
    3. 打印结果, print(result)
  • 使用 apply 函数调用对象
    1. 定义一个函数,例如 def add(x, y): return x + y
    2. 准备参数, args = (3, 4)
    3. 调用 apply 函数, result = apply(add, args)
    4. 打印结果, print(result)

3.2 语句操作步骤

  • 使用 assert 语句进行断言
    1. 定义一个变量,例如 age = 25
    2. 使用 assert 语句进行判断, assert age < 20
    3. 如果条件不满足,会抛出 AssertionError 异常。
  • 使用 for 语句进行循环
    1. 定义一个序列,例如 numbers = [1, 2, 3, 4, 5]
    2. 使用 for 语句遍历序列, for num in numbers: print(num)

通过以上介绍,我们对 Jython 的内置函数和语句有了更深入的了解。合理使用这些函数和语句可以提高代码的效率和可读性。

4. 更多内置函数详解

4.1 数据类型转换函数

函数 描述 语法 示例
float 将参数转换为浮点数类型 float(x) python<br>>>> float(2) # int to float<br>2.0<br>>>> float(7L) # long to float<br>7.0<br>>>> float(abs(1.1 + 2.1j))<br>2.3706539182259396<br>>>> float("2.1") # string to float<br>2.1<br>
int 将参数转换为整数类型,可指定进制 int(x[, base]) python<br>>>> int(3.5) # float to int<br>3<br>>>> int(5L) # long to int<br>5<br>>>> int(abs(2.2 + 1.72j)) # complex to int<br>2<br>>>> int("012", 8) # octal string to int<br>10<br>>>> int("0x1A", 16) # hex string to int<br>26<br>
long 将参数转换为长整数类型,可指定进制 long(x, base) python<br>>>> long(2.7) # float to long<br>2L<br>>>> long(abs(1.1 + 2.3j)) # complex to long<br>2L<br>>>> long("021", 8) # octal string to long<br>17L<br>>>> long("0xff", 16) # hex string to long<br>255L<br>
str 返回对象的字符串表示形式 str(object) python<br>>>> str(1) # int to string<br>'1'<br>>>> str(4L) # long to string<br>'4'<br>>>> str(2.2 + 1.3j)<br>'(2.2 + 1.3j)'<br>>>> from java.util import Vector<br>>>> str(Vector)<br>'java.util.Vector'<br>>>> v = Vector()<br>>>> str(v)<br>'[]'<br>>>> v.add(type) # put a function in the vector<br>1<br>>>> str(v)<br>'[<java function type at 5229978>]'<br>

4.2 集合操作函数

函数 描述 语法 示例
filter 根据函数筛选序列元素,返回满足条件的元素列表 filter(function, sequence) python<br>>>> filter(lambda x: x % 2, [1, 2, 3, 4, 5, 6, 7, 8, 9])<br>[1, 3, 5, 7, 9]<br>>>> filter(None, [1, 0, [], 3 - 3, {}, 7])<br>[1, 7]<br>
map 对序列中的每个元素应用函数,返回结果列表 map(function, sequence[, sequence, ...]) python<br>>>> map(None, range(6), ["a", "b", "c"])<br>[(0, 'a'), (1, 'b'), (2, 'c'), (3, None), (4, None), (5, None)]<br>>>> def pad(string):<br>... return string.rjust(10)<br>...<br>>>> map(pad, ["a", "b", "c", "d"])<br>[' a', ' b', ' c', ' d']<br>
zip 返回由最短序列长度决定的元组列表,元组包含相同索引的元素 zip(seq1 [, seq2 [...]]) python<br>>>> zip([1, 2, 3, 4, 5, 6, 7], "abcdefg")<br>[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g')]<br>>>> zip(range(5), range(5, -1, -1))<br>[(0, 5), (1, 4), (2, 3), (3, 2), (4, 1)]<br>

4.3 集合操作函数调用流程

graph TD;
    A[选择集合操作函数] --> B{函数类型};
    B -- 筛选 --> C[调用 filter 函数];
    B -- 映射 --> D[调用 map 函数];
    B -- 组合 --> E[调用 zip 函数];

5. 更多语句详解

5.1 异常处理与文件操作语句

语句 描述 语法 示例
try/except Jython 的异常处理机制,类似于 Java 的 try/catch `”try:” code-block “except” [expression [“,” target]] “:” code-block [“else:” code-block] OR “try:” code-block “finally:” code-block python<br>>>> try:<br>... 1 / 0<br>... except ZeroDivisionError, e:<br>... print "You cannot divide by zero: ", e<br>...<br>You cannot divide by zero: integer division or modulo<br>>>> try:<br>... pass<br>... finally:<br>... print "This block always executes"<br>...<br>This block always executes<br>
execfile 执行包含 Jython 代码的文件 execfile(filename[, globals[, locals]]) python<br>>>> # first use an anonymous dictionary for globals<br>>>> execfile("c:\\windows\\desktop\\testfile.py", {})<br>a b 7<br>>>> globals()<br>{'__name__': '__main__', '__doc__': None}<br>>>> # Now use current namespaces<br>>>> execfile("c:\\windows\\desktop\\testfile.py")<br>a b 7<br>>>> globals()<br>{'var2': 'b', 'var1': 'a', '__doc__': None, 'var3': 7, '__name__': '__main_'}<br>
open 打开指定文件并返回文件对象 open(filename[, mode[, buffering]]) python<br>>>> # open file in current directory for reading plus writing.<br>>>> fo = open("config.cfg", "r+")<br>>>> # Open file for binary reading<br>>>> fo = open("c:\soot\baf\Baf.class", "rb")<br>

5.2 异常处理与文件操作语句执行流程

graph TD;
    A[程序遇到相关语句] --> B{语句类型};
    B -- 异常处理 --> C[执行 try/except 语句];
    B -- 文件执行 --> D[执行 execfile 语句];
    B -- 文件打开 --> E[执行 open 语句];

6. 综合示例

6.1 综合操作步骤

  • 使用 filter map 函数处理序列
    1. 定义一个序列,例如 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    2. 使用 filter 函数筛选出奇数, odd_numbers = filter(lambda x: x % 2, numbers)
    3. 定义一个函数,例如 def square(x): return x * x
    4. 使用 map 函数对奇数序列应用该函数, squared_odd_numbers = map(square, odd_numbers)
    5. 打印结果, print(squared_odd_numbers)
  • 使用 try/except 语句处理异常并结合文件操作
    1. 尝试打开一个不存在的文件, try: file = open("nonexistent.txt", "r")
    2. 捕获 IOError 异常, except IOError, e: print "Error opening file: ", e
    3. 如果文件打开成功,进行相关操作,例如读取文件内容。

通过对 Jython 内置函数和语句的全面了解和实践操作,开发者可以更加灵活地运用 Jython 进行编程,提高开发效率和代码质量。无论是简单的数据处理还是复杂的程序逻辑,合理使用这些函数和语句都能让代码更加简洁、高效。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值