[英]Calling Python method with two defined parameters, but passing only one variable
我正在努力理解以下代码片段:
@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])
。 我基于他的docstring文本function should take two points (each lists of length 2) and return some....
但是由于有了装饰器,您还可以使用shape
调用函数area
。 这是因为在执行任何操作之前,将调用metric
并重新排列shape
以便仅在两个“点”上调用area
。 因此,您需要做的是找到shape
,然后用它来shape
centroid
。 我不愿意更深入地了解shape
到底是什么或如何使代码正常工作,因此,如果其他人拉出代码并进行测试,则需要接受他的回答。
另外,您可以想到的装饰器通常的方式是,它们接受一个函数,可能先做一个事情,然后调用该函数,然后再做一个之后的事情。 它们返回一个函数,以便当您启动程序时,您装饰的函数将被具有相同名称的这个新函数“替换”,但可能还会做其他/不同的事情。 见这为更多的装饰。
为了后代-这是在注释中,并进行了一些编辑以适合答案的形式,之后删除注释。 我也喜欢积分。
您的函数area(prev, nxt)
有两个参数,但是在centroid(points)
函数中,您将变量a
分配为area(prev, nxt)
函数的结果,但您只传递了一个参数即points
。
def centroid(points):
a = area(points, secondArgumentNeedsToGoHere)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.