Home > Net >  How to create a method that can be called by any instance that uses information from the instances?
How to create a method that can be called by any instance that uses information from the instances?

Time:04-14

Suppose I want to create a class called "Point". Suppose I only ever plan on making two points because that's important. I want to create a method that can be called by either instance or "point" that gives the distance between the two points. How would I go about doing that?

This is what my code looks like.

import math

class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def distance(self): # Just filler code
        return math.sqrt((self_2.x - self_1.x)**2 (self_2.y - self_1.y)**2) # Just filler code

point_1 = Point(0,0)
point_2 = Point(3,4)

print(point_1.distance()) # Should return 5.0
print(point_2.distance()) # Should return 5.0

Obviously I know what I made here doesn't work, but I'm just trying to give an idea of what the print statement should do. How would I go about doing this?

CodePudding user response:

import math

class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def distance(self,other):
        return math.sqrt((self.x - other.x)**2 (self.y - other.y)**2)

point_1 = Point(0,0)
point_2 = Point(3,4)

print(point_1.distance(point_2)) # Should return 5.0
print(point_2.distance(point_1)) # Should return 5.0

CodePudding user response:

You should use a second class that specifically represents two points.

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

    def distance_to(self, other):
        return abs(complex(self.x, self.y) - complex(other.x, other.y))

class PointPair:
    def __init__(self, p1, p2):
        self.p1 = p1
        self.p2 = p2

    def distance(self):
        return self.p1.distnace_to(self.ps2)


point_1 = Point(0,0)
point_2 = Point(3,4)
pair = PointPair(point_1, point_2)
print(pair.distance()

or a regular function

def distance(p1, p2):
    return abs(complex(p1.x, p1.y) - complex(p2.x, p2.y))


print(distance(point_1, point_2))
  • Related