Calculating Euclidean distance using Magic Methods in Python 3

后端 未结 4 513
广开言路
广开言路 2021-01-23 14:46

I have a code that calculates Euclidean distance for me:

class Point:
    \"\"\"A point in two-dimensional space.\"\"\"

    def __init__(self, x, y):
        se         


        
4条回答
  •  天涯浪人
    2021-01-23 15:27

    Your second class works for me. I do not see any issues with it:

    In [9]: class Point_1(object):
       ...:     
       ...:     def __init__(self, x, y):
       ...:         self._x = x
       ...:         self._y = y
       ...:   
       ...:     
       ...:     def setX(self, x,y):
       ...:         self._x = x
       ...:         self._y = y
       ...:  
       ...:     def getX(self):
       ...:         return self._x,self._y
       ...:     
       ...:     
       ...:     def __sub__ (self, other ):
       ...:         return Point_1(self._x - other._x, self._y - other._y)
       ...:     
       ...:     def __pow__(self,p):
       ...:         return Point_1(self._x ** p, self._y **p)
    

    And then:

    In [14]: p1 = Point_1(10,4)
        ...: print(p1.getX())
        ...: 
        ...: p2 = Point_1(3,1)
        ...: print(p2.getX())
        ...: 
        ...: p3 = p1 - p2
        ...: 
        ...: 
    (10, 4)
    (3, 1)
    
    In [15]: p3.getX()
    Out[15]: (7, 3)
    

    Call it vector or point or whatever, it seems to be doing what you want it to do.

提交回复
热议问题