Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 distanceFromOther(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 distanceFromOther().
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.distanceFromOther(2,3)


a.distanceFromOther(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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading