我正在努力理解以下代码片段:
@metric
def area(prev, nxt):
"""Area of a polygon with points in clockwise order."""
return area_piece(prev, nxt) / 2
def centroid(points):
a = area(points)
return [center_x_helper(points)/a, center_y_helper(points)/a]
@metric
def center_x_helper(prev, nxt):
return (prev[0] + nxt[0]) * area_piece(prev, nxt) / 6
@metric
def center_y_helper(prev, nxt):
return (prev[1] + nxt[1]) * area_piece(prev, nxt) / 6
def area_piece(prev, nxt):
return nxt[0] * prev[1] - prev[0] * nxt[1]
完整的代码位于此处。
我假设这points
是某种2D数组/列表,其中每个项目都包含一对X和Y坐标。但是不知何故,points
它传递给area(prev, nxt)
每对坐标来执行计算。
当我尝试以下其中一项时
centroid([[150, 200], [0, 300], [0, 400], [3, 1]])
centroid([150, 200, 0, 300, 0, 400, 3, 1])
我收到此错误:
TypeError: area() missing 1 required positional argument: 'nxt'
我是否在这里丢失了某些内容,或者此代码根本无法以这种方式运行?
我认为您遇到的问题不是以正确的格式发送列表。
我不知道完整的代码从哪里来shape
。centroid
被调用时发生的是area
被调用。但是在实际执行区域之前,metric
将调用装饰器(原始代码中的第77行)。metric
然后重新排列points
调用的输入列表(第85、86行),然后area
在这些重新排列的列表上调用原始函数。
度量标准不作用于“点”,而是与一种叫做shape
“定义”的东西一起工作,我找不到它,但必须在原始代码中的某个地方。有很多的方法,shape
具有不属于名单的一部分,例如.points
,.parts
,.tolist
等...
因为area
您需要发送两个“点”,它们似乎只是长度为2的列表,如下所示:area([1,2], [4,5])
。我基于他的文档字符串文本function should take two points (each lists of length 2) and return some....
但由于装饰,你也可以调用函数area
用shape
。这是因为在做任何事情之前,它都会metric
被调用并shape
重新安排,这样area
就只能在两个“点”上调用它。因此,您需要做的是查找内容shape
,然后进行调用centroid
。我不愿意更深入地查找确切的shape
内容或如何使代码正常工作,因此,如果其他人拉出代码并进行测试,则需要接受他的回答。
另外,您可以想到的装饰器通常的方式是,它们接受一个函数,可能先做一个事情,然后调用该函数,然后再做一个之后的事情。它们返回一个函数,以便当您启动程序时,您装饰的函数将被具有相同名称的这个新函数“替换”,但是可能还会做其他/不同的事情。见这为更多的装饰。
为了后代-这是在注释中,并进行了一些编辑以适合答案的形式,之后删除注释。我也喜欢积分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句