Jenifer J
Jenifer J

Reputation: 15

finding distance between two points in python, passing inputs via two different objects

I have to write a code to find the different between two point by passing value via two objects as below. But I am getting TypeError: init() missing 3 required positional arguments: 'x', 'y', and 'z'

class Point:
    def __init__(self, x, y,z):
        self.x = x
        self.y = y
        self.z = z

    def __str__(self):
        return '(point: {},{},{})'.format(self.x, self.y, self.z)

    def distance(self, other):
        return sqrt( (self.x-other.x)**2 + (self.y-other.y)**2 + (self.z -other.z)**2 )      


p = Point()

p1 = Point(12, 3, 4)

p2 = Point(4, 5, 6)

p3 = Point(-2, -1, 4)

print(p.distance(p1,p3))

Upvotes: 0

Views: 729

Answers (3)

Falx
Falx

Reputation: 211

The problem comes from this line:

p = Point()

When you defined you class, you specified it has to be passed 3 parameters for it to be initialised (def __init__(self, x, y,z)).

If you still want to be able to create this Point object without having to pass those 3 parameters, you can make them optional like this :

def __init__(self, x=0, y=0, z=0):
    self.x = x
    self.y = y
    self.z = z

This way, if you were to not specify these parameters (as you did), it will create a point with coordinates {0, 0, 0} by default.

Upvotes: 1

Meto
Meto

Reputation: 658

class Point:
    def __init__(self, x, y,z):
        self.x = x
        self.y = y
        self.z = z

    def __str__(self):
        return '(point: {},{},{})'.format(self.x, self.y, self.z)

    def distance(self, other):
        return math.sqrt( (self.x-other.x)**2 + (self.y-other.y)**2 + (self.z -other.z)**2 )

p1 = Point(12, 3, 4)

p2 = Point(4, 5, 6)

p3 = Point(-2, -1, 4)

print(Point.distance(p1,p3))

It works like this.You should not define a P point seperate than the other three points. Every point is a seperate instance. But when you try to use the function just call the class.

Upvotes: 0

Kuldeep Singh Sidhu
Kuldeep Singh Sidhu

Reputation: 3856

You are not passing the required 3 arguments for p = Point()

fixed your errors

from math import sqrt
class Point:
    def __init__(self, x, y,z):
        self.x = x
        self.y = y
        self.z = z

    def __str__(self):
        return '(point: {},{},{})'.format(self.x, self.y, self.z)

    def distance(self, other):
        return sqrt( (self.x-other.x)**2 + (self.y-other.y)**2 + (self.z -other.z)**2 )      


# p = Point() # not required

p1 = Point(12, 3, 4)

p2 = Point(4, 5, 6)

p3 = Point(-2, -1, 4)

print(p1.distance(p3)) # use this to find distance between p1 and any other point

# or use this
print(Point.distance(p1,p3))

Upvotes: 0

Related Questions