Skip to content
Advertisement

Do you know how to input the object from the same class in python?

I am python beginner.

I have to define a method distanceFromOther() that takes the different dot as a factor and returns the distance between itself and the other point.

Class Point is for treating points (x,y) in a two-dimensional plane as objects.

This is the code that I made.

import math

class Point:

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


        def dFO(self, a, b):
            self.a = a
            self.b = b
    
            otResult = math.sqrt(math.pow(self._x-self.a,2)+math.pow(self._y-self.b,2))
            return otResult


        def __str__(self):
            return f"({self._x}, {self._y})"

I made two objects a and b.

a = Point(1,1)
b = Point(2,3)

I have to figure out the distance between a and b using method dFO(). I should input ‘b’ as factor, but I made the method to put the values of points x,y. I don’t know how to input object ‘b’ that I made as the factor.

a.dFO(2,3)


a.dFO(b)

The former is what I made, and the latter is what I want to make.

If you know how to do it, please help me!

Advertisement

Answer

You just need to access the _x and _y attributes:

import math

class Point:

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

        def distanceFromOther(self, b):
            x = b._x
            y = b._y
    
            otResult = math.sqrt(math.pow(self._x-x,2) + math.pow(self._y-x,2))
            return otResult

        def __str__(self):
            return f"({self._x}, {self._y})"

Also, you don’t need to convert parameters of a method into attributes of that object.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement