如何通过使用数组中的索引来使用作为函数中对象实例的 python 数组的元素?

How can I use an element of a python array that is an instance of an object in a function by using the index into the array?

我有一个任务,我要确定一个 Point(x,y) 是否比存储在 Python 数组中的任何点更近。这是测试代码:

from point import *

collection = []

p1 = Point(3,4)
collection.append(p1)

print(collection)
p2 = Point(3,0)
collection.append(p2)

print(collection)

p3 = Point(3,1)

radius = 1

print( collection[1] ) #  This works, BTW

p = collection[1]
print( p )     #  These two work also!

for i in collection:
  p = collection[i]   # THIS FAILS
  if distance(p3,p) < 2*radius:
    print("Point "+collection[i]+" is too close to "+p3)

文件 point.py 包含:

import math


class Point:
    '''Creates a point on a coordinate plane with values x and y.'''

    COUNT = 0

    def __init__(self, x, y):
        '''Defines x and y variables'''
        self.X = x
        self.Y = y

    def move(self, dx, dy):
        '''Determines where x and y move'''
        self.X = self.X + dx
        self.Y = self.Y + dy

    def __str__(self):
        return "Point(%s,%s)"%(self.X, self.Y)

    def __str__(self):
     return "(%s,%s)"%(self.X,self.Y)

def testPoint(x=0,y=0):
   '''Returns a point and distance'''
   p1 = Point(3, 4)
   print (p1)
   p2 = Point(3,0)
   print (p2)
   return math.hypot(p1, p2)

def distance(self, other):
   dx = self.X - other.X
   dy = self.Y - other.Y
   return math.sqrt(dx**2 + dy**2)

#p1 = Point(3,4)
#p2 = Point(3,0)

#print ("p1 = %s"%p1)
#print ("distance = %s"%(distance(p1, p2)))

现在,我有几个问题可以帮助我理解。

  1. 在测试用例中,为什么数组的打印不用str函数来 将 Point 打印为 '(x,y)'?
  2. 在“if distance(p3,collection[i])”中,为什么 collection[i] 没有被识别为距离函数所期望的点?
  3. 在'p = collection[i]'语句中,为什么python抱怨列表索引必须是整数或切片,而不是点?

集合数组似乎未被识别为 Point 实例数组。我对 Objective-C 或 Java 等其他 OO 语言感到困惑,这些都是简单的事情。

  1. 看看this question__repr__() 用于在列表中呈现内容。

  2. (和 3.)我不确定我是否听懂了你的问题,但你的代码中存在的问题是 Python 将对象本身交给你,而不是索引.所以:

for i in collection:
  p = collection[i]   # THIS FAILS
  if distance(p3,p) < 2*radius:
    print("Point "+collection[i]+" is too close to "+p3)

应该是:

for p in collection:
  if distance(p3,p) < 2*radius:
    print(f"Point {p} is too close to {p3}")