RSS
热门关键字:  java  Ajax  JSP  JSF  Struts
当前位置 : 首页>Java>列表

Jython:Java的Python

来源: 作者: 时间:2007-08-08 点击:
eval built-in function is used to parse and evaluate constructed expressions all at once, saving us from having to write an expression evaluator from scratch.

首先请注意,这是纯正的Python代码: Jython脚本与本书一直在用的语言核心是相同的。这是好事,既因为Python是如此简单,也因为你不必再去学习一门新的,私有的语言。这也意味着可以使用Python所有的高级语法与工具。例如,在这个脚本中,使用了Python内建函数eval,分析与计算表达式同时完成,我们就不必从零开始写表达式计算器了。

18.4.4. Interface Automation Tricks

18.4.4. 接口自动化的窍门

The previous calculator example also illustrates two interface automations performed by Jython: function callback and attribute mappings. Java programmers may have already noticed that this example doesn't use classes. Like standard Python and unlike Java, Jython supports but does not impose object-oriented programming (OOP). Simple Python functions work fine as callback handlers. In Example 18-5, assigning key.actionPerformed to a Python function object has the same effect as registering an instance of a class that defines a callback handler method:

上面的计算器也同时示例了Jython所做的两个接口自动化:函数回调与属性映射。Java程序员可能已经注意到这个例子并没有使用类。不像Java而更像标准Python,Jython支持但不强制面向对象编程(OOP)。简单的Python函数就可以作为回调处理器。在例18-5中,key.actionPerformed赋值为一个Python函数对象,效果就像注册一个具有回调处理函数的类:

def push(event):
    ...
key 
= swing.JButton(label)
key.actionPerformed 
= push

This is noticeably simpler than the more Java-like:

这比Java的方式简单的多:

class handler(awt.event.ActionListener):
    def actionPerformed(self, event):
        ...
key 
= swing.JButton(label)
key.addActionListener(handler( ))

Jython automatically maps Python functions to the Java class method callback model. Java programmers may now be wondering why we can assign to something named key.actionPerformed in the first place. Jython's second magic feat is to make Java data members look like simple object attributes in Python code. In abstract terms, Jython code of the form:

Jython自动将Python函数映射为Java的回调类。Java程序员现在可能还会问,为什么能直接赋值给key.actionPerformed?Jython的另一神功是让Java的数据成员看起来像Python代码中简单的对象属性。简单来说就是,以下 Jython代码:

 
= Object(argument)
X.property 
= value + X.property

is equivalent to the more traditional and complex Java style:

等效于传统的Java风格的复杂代码:

= Object(argument)
X.setProperty(value 
+ X.getProperty( ))

That is, Jython automatically maps attribute assignments and references to Java accessor method calls by inspecting Java class signatures (and possibly Java BeanInfo files if used). Moreover, properties can be assigned with keyword arguments in object constructor calls, such that:

也就是说,Jython自动将属性赋值与引用映射为Java的存取函数,这是通过检查Java类签名实现的(如果存在,也会检查Java BeanInfo文件)。而且,属性可以在对象构造函数调用时,使用关键字参数进行赋值,如:

= Object(argument, property=value)
 

is equivalent to both this more traditional form:

等效于传统形式:

最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册