So I am trying to write make a function that will initialize two points and output previously made methods.
Partial code below:
class Point(Geometry):
next_id = 0
def __init__(self,x,y,):
self.x = x
self.y = y
self.id = Point.next_id
Point.next_id += 1
def __str__(self):
return "(%0.2f, %0.2f)" % (self.x, self.y)
def quadrat(self):
if (self.x > 0 and self.y > 0):
return "Quad I"
elif (self.x < 0 and self.y > 0):
return "Quad II"
elif (self.x < 0 and self.y < 0):
return "Quad III"
elif (self.x > 0 and self.y < 0):
return "Quad IV"
elif (self.x == 0 and self.y == 0):
return "Origin"
elif (self.x == 0):
return "Y-axis"
elif (self.y == 0):
return "X-axis"
def distance(p0, p1):
dist = math.sqrt((p0.x - p1.x)**2 + (p0.y - p1.y)**2)
return dist
def equality():
if (self.x == self.y):
print "True"
else:
print "False"
def identify():
if(p0.id == p1.id):
print "True"
else:
print "False"
def pointTest():
global P1,P2
P1 = Point(-3,-3)
P2 = Point(0,0)
print "P1) ID =", P1.id,", Coordinates=", P1,", Location=",P1.quadrat()
print "P2) ID =", P2.id,", Coordinates=", P2,", Location=",P2.quadrat()
print "Distance between",P1,"and",P2,"is %0.2f" % (P1.distance(P2))
print "P1==P2?",P1==P2
print "P1 same as P2?",P1.id==P2.id
P1 = None
P2 = None
print pointTest()
When my points are defined outside the method and when the print
statements are outside the method, my output comes out perfectly.
But I need the points to be initialized in the method and my print
statement to be within the method as well.
When I call it, I get the error that pointTest
is not defined.
My output needs to look like this:
<<<< print pointTest
Which will give me the answers to my print statements.
If you need to initialize your variables in a different method from __init__
, then you must either pass them to the initialization method and access their attributes directly:
def pointTest(p1, p2):
p1.x = -3
p1.y = -3
p2.x = 0
p2.y = 0
p1 = Point()
p2 = Point()
pointTest(p1, p2)
or declare them as global variables, which is generally a bad idea but can be a quick workaround:
def pointTest():
global p1, p2
p1 = Point(-3, -3)
p2 = Point(0, 0)
p1 = None
p2 = None
pointTest()
In both cases, you can add the call to print
inside of the pointTest
method.
Note that in the second case, you don't need to declare p1
and p2
as None
, but it's better to make every variable explicit. You don't want your methods to make global variables pop out, that you weren't aware of.
It seems that in addition, your pointTest
method appears as undefined.
Regarding your original indentation, it seems that your pointTest
method is indeed inside of a code block.
Therefore, the pointTest
method is probably declared only in a deeper scope than where you call it, and thus, is not defined. Either put it outside of that block, or put all your consequent print
s in that block.