Home > other >  How can I use an element of a python array that is an instance of an object in a function by using t
How can I use an element of a python array that is an instance of an object in a function by using t

Time:02-19

I have a task wherein I am to determine if a Point(x,y) is closer than some amount to any of the Points that are stored in a Python array. Here is the test code:

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)

The file point.py contains:

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)))

Now, I have a couple of questions here to help me understand.

  1. In the test case, why doesn't the print of the array use the str function to print the Point out as '(x,y)'?
  2. In ' if distance(p3,collection[i]) ', why isn't collection[i] recognized as a Point which the distance function is expecting?
  3. In the 'p = collection[i]' statement, why does python complain that the list indices must be integers or slices, not Point?

It appears that the collection array is not recognized as an array of Point instances. I'm confused as in other OO languages like Objective-C or Java, these are simple things to do.

CodePudding user response:

  1. Take a look at this question. __repr__() is used when rendering things in lists.

  2. (and 3.) I'm not sure if I follow your questions, but the problem you have in your code is that Python hands you the object itself, not the index. So:

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

should be:

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