Jython 中的用户自定义函数与变量作用域深度解析
1. 函数定义
在 Jython 里,函数属于可调用对象,既能够独立于类存在,也会在类定义中出现,通过对象属性查找转变为方法。Jython 允许无类函数的存在,并且把函数当作一等对象,这意味着函数能够动态创建,还能作为参数或返回值传递。下面是 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
Local variab