我还在苦苦挣扎。此代码作为对Python: closest coordinate?的回答提交。很多事情让我困惑,但我已经完成了大部分工作。浮点法的使用self
对我来说仍然有点棘手(我得到了self.x
和self.y
,但并不确定在这种情况下自我是什么)。只是提到,因为它可能涉及主要部分,我不明白,这是closest
方法中的lambda函数。我发现它会返回生成的最小项目,并且它将参数解包为参数。然后我有点失落。分别是__sub__
和__pow__
分别重新定义了-
和**
,还是它们只是不同的方法?这个lambda函数做什么?
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def closest(self,*points):
return min(points,key=lambda x:float(x-self))
def __sub__(self,other):
return Point((self.x-other.x) , (self.y - other.y))
def __pow__(self,powTo):
return Point(self.x**powTo,self.y**powTo)
def __iter__(self):
yield self.x
yield self.y
def __float__(self):
return sum(self**2)**0.5
def __str__(self):
return "(%s,%s)"%(self.x,self.y)
pt0 = Point(9,2)
print pt0.closest(Point(0,0),Point(10,0),Point(10,10))
你尝试打印自壁橱或'打印(自点[1])'' – 2014-12-10 21:49:16
self'是值该方法被调用,例如当你使用'pt0.closest(...)'时,'pt0'。 – Barmar 2014-12-10 21:49:23
这些特殊方法的文档在这里:https://docs.python.org/2/library/operator.html – Barmar 2014-12-10 21:51:51