Jython 中的用户自定义函数与变量作用域详解
1. 函数定义
在 Jython 里,函数是可调用对象,它既可以独立于类存在,也能在类定义中作为方法。Jython 支持无类函数,这与 Java 不同,并且 Jython 中的函数属于一等对象,能动态创建,还可作为参数或返回值传递。
1.1 函数语法
Jython 函数的语法如下:
"def" function__name([parameter_list])":"
code block
函数名需为无空格的字母数字字符串,且首字符为字母或下划线 _
,名称区分大小写。要注意避免与内置函数重名,例如定义名为 type
的函数会使内置 type
函数不可用:
>>> S = "A test string"
>>> type(S) # test the built-in type()
<jclass org.python.core.PyString at 6879429>
>>> def type(arg):
... print "Not the built-in type() function"
... print "Local variables: ", vars() # look for "arg"
...