Jython高级类特性深度解析
在Jython编程中,特殊属性是创建高度定制化、行为复杂对象的关键。这些以双下划线开头和结尾的标识符,广泛存在于Jython类中,能让我们以较少的代码实现强大的功能,提升设计的灵活性和可复用性。
预定义类属性
类和实例隐式拥有一些特殊属性,这些属性在类定义执行或实例创建时自动出现。Jython类有五个特殊属性,而Java类有其中三个。这些属性大多可读,但只有部分可赋值。
以 LineDatum
类为例,它定义在 datum.py
文件中,用于跟踪直线上的点:
# file: datum.py
import java
class LineDatum(java.util.Hashtable):
"""Collects points that lie on a line.
Instantiate with line slope and intercept: e.g. LineDatum(.5, 3)"""
def __init__(self, slope, incpt):
self.slope = slope
self.incpt = incpt
def addPoint(self, x, y):
"""addPoint(x, y) – > 1 or 0
Accepts coordinates for a cartesian point (x,y). If point is
o