Reputation: 17
On executing the below code
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self,x1,y1,x2,y2):
d = math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2))
print ("Distance between the points is " + "%0.6f" % d)
return d
def main():
x = float(input("Enter x coordinate of first circle's centre: "))
y = float(input("Enter y coordinate of the first circle's centre: "))
r = float(input("Enter first circle's radius: "))
pointx1 = x
pointy1 = y
first_circle = circle(x, y, r)
print(first_circle)
x = float(input("\nEnter x coordinate of second circle's centre: "))
y = float(input("Enter y coordinate of the second circle's centre: "))
r = float(input("Enter second circle's radius: "))
pointx2 = x
pointy2 = y
second_circle = circle(x, y, r)
Point.distance(Point,pointx1, pointy1, pointx2, pointy2)
I get the following error:
File "C:/Users/Deepak/PycharmProjects/Submission/Shapes.py",line 102,in main
Point.distance(Point,pointx1, pointy1, pointx2, pointy2)
TypeError: unbound method distance() must be called with Point instance as
first argument (got classobj instance instead)
I am trying to read the center coordinates and radius of two circles from the user and then I am trying to determine the distance between their centers.I tried sending only four parameters to Point.distance() but that also returned an error. Please help.What should I do to resolve this error.
Upvotes: 1
Views: 155
Reputation: 4043
I am not sure if you got wrong what I think you might got wrong, but you do not pass an argument for self
, you only pass pointx1, pointy1, pointx2, pointy2
, the self
is handled internally. Actually your distance function is not really taking advantage of the class structure. You might think of, e.g.:
from math import sqrt
class Point(object):
def __init__(self,x,y):
self.x=x
self.y=y
@classmethod
def two_point_distance(cls, pnt1, pnt2):
return sqrt( ( pnt1.x - pnt2.x )**2 + ( pnt1.y - pnt2.y )**2 )
def distance_to(self, pnt2):
return sqrt( ( self.x - pnt2.x )**2 + ( self.y - pnt2.y )**2 )
pntA=Point(3, 2)
pntB=Point(7, 8)
print Point.two_point_distance( pntA, pntB )
print pntA.distance_to( pntB )
Upvotes: 1