[英]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)))
现在,我有几个问题可以帮助我理解。
集合数组似乎未被识别为 Point 实例数组。 我对其他 OO 语言(如 Objective-C 或 Java)感到困惑,这些都是简单的事情。
看看这个问题。 __repr__()
在列表中呈现事物时使用。
(和 3.)我不确定我是否听懂了你的问题,但你在代码中遇到的问题是 Python 给你 object 本身,而不是索引。 所以:
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}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.