Jython 中的用户自定义函数与变量作用域
1. 函数基础
在 Jython 里,函数属于可调用对象,既能够独立于类存在,也能在类定义中以方法的形式呈现。Jython 把函数视为一等对象,这意味着函数可以动态创建,还能作为参数传递或者作为返回值返回。
1.1 函数定义
Jython 函数的定义语法如下:
def function__name([parameter_list]):
code block
函数名可以是任意不含空格的字母数字字符串,但首字符必须是字母或者下划线 _
,并且名称区分大小写。在定义函数名时,要注意避免与其他函数(尤其是内置函数)重名。例如:
>>> 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"
...
>>> type(S)
Not the built-in type() function
Loca