1

我正在用 eclipse SWT/JFace 编写 jython 应用程序。我必须将浮点数组传递给 java 对象才能从中取回一些值。我正在使用 jarray 包。有更多的pythonic方法吗?

bounds = zeros(4, 'f')
# from java org.eclipse.swt.graphics.Path.getBounds(float[] bounds)
path.getBounds(bounds)
# from java org.eclipse.swt.graphics.Rectangle(int x, int y, int width,int height)
rect = Rectangle(int(round(bounds[0])), 
                     int(round(bounds[1])),
                     int(round(bounds[2])),
                     int(round(bounds[3])))
4

3 回答 3

4

也许。首先,您可以稍微减少代码:

bounds = map(lambda v: int(round(v)), bounds)

这避免了重复的演员阵容。我的下一步是创建一个辅助方法来将数组转换为Rectangle,因此您不必重复此代码:

def toRectangle(bounds):
    bounds = map(lambda v: int(round(v)), bounds)
    return Rectangle(bounds[0], bounds[1], bounds[2], bounds[3])

那会给你留下:

rect = toRectangle(path.getBounds(zeroes(4, 'f'))

或者,创建一个直接接受路径的辅助函数。

或者你可以猴子补丁路径:

def helper(self):
    bounds = zeros(4, 'f')
    self.getBounds(bounds)
    bounds = map(lambda v: int(round(v)), bounds)
    return Rectangle(bounds[0], bounds[1], bounds[2], bounds[3])

org.eclipse.swt.graphics.Path.toRectangle = helper

rect = path.toRectangle()

请注意,这可能有点错误。如果它不起作用,请查看classmethod()new.instancemethod()了解如何动态地将方法添加到类中。

于 2009-08-12T07:48:43.103 回答
4

如今,列表推导式的使用被认为更符合 Python 风格:

rounded = [int(round(x)) for x in bounds]

这将为您提供一个四舍五入的整数列表。当然,您可以将其分配给边界而不是使用“舍入”

bounds = [int(round(x)) for x in bounds]

在我们的邮件列表中,Charlie Groves 指出,整个事情都可以用 * 操作符展开,如下所示:

rect = Rectangle(*[int(round(x)) for x in bounds])
于 2009-08-12T13:09:06.590 回答
2

还值得指出的是,没有必要使用零来创建数组。您可以使用包含可以转换为正确类型的实例的 Python 可迭代对象调用 getBounds:

path.getBounds([0, 0, 0, 0])
于 2009-08-15T20:20:28.153 回答