I'm new to python, and programming in general and am struggling to understand why I can't access the x, y coordinates of the list I created ranlist
to use as variables in my math module distance formula.
Here is the entirety of my code, however the step of defining the function closestpt
is where I am hung up, and within the function, ranlist.x
, ranlist.y
is where I get an
AttributeError: list object has no attribute 'x'
Can someone explain to me why ranlist
does not have 'x' and 'y' as attributes, and how I can access the x,y points in the list ranlist
? When I step through the code and debug I can see the random float values generated
import math
class Point():
def __init__(self, x, y, z=0):
self.x=x
self.y=y
self.z=z
self.dem=2
if (z!=0):
self.dem=3
def print_coordinate(self):
print "The x coordinate is %s, the y coordinate is %s, and the z coordinate is %s" % (self.x, self.y, self.z)
def calc_distance(self, next1):
try:
if (self.z==0):
dx = self.x - next1.x
dy = self.y - next1.y
return math.hypot(dx,dy)
else:
threedist = ((self.x - next1.x)^2 + (self.y - next1.y)^2 + (self.z - next1.z)^2)
return math.sqrt(threedist)
except(SyntaxError, IndexError, TypeError) as e:
print e
cord1 = Point(0,1,4)
cord2 = Point(0,4,0)
print cord1.print_coordinate()
print cord1.calc_distance(cord2)
import random
a = 10
b = 20
val = random.uniform(a,b)
ranlist = []
def ranpoint(num_point, dimension, lower_bound, upper_bound):
for i in range(num_point):
x = random.uniform(lower_bound, upper_bound)
y = random.uniform(lower_bound, upper_bound)
ranlist.append(Point(x,y,0))
return ranlist
print ranpoint
print ranpoint(100, "2d", 0, 100)
rantest = ranpoint(100, '2d', 0, 100)
def closestpt():
cordt = Point(50,50)
dist1 = []
for i in range(0, 100):
ndx = cordt.x - ranlist.x
ndy = cordt.y - ranlist.y
dist2 = math.hypot(ndx,ndy)
dist1.append(dist2)
return dist1
print closestpt()
You have ranlist
which is a list
. You append
a Point
to it. So now ranlist
has 1 object inside it of type Point
.
To access this object you could run ranlist[0].x
and ranlist[0].y
which will access the first member of the list (in index 0
) and retrieve the value of x
and y
respectively.