如何添加距离方法

时间:2018-08-18 15:34:34

标签: python python-3.x

我有以下代码:

#file.txt:
#Hello
#My name is John Smith
#How are you?

File.open("file.txt").each do |line|
   puts line
   puts line.linenumber
end

#First Iteration outputs
#=> Hello
#=> 1

#Second Iteration outputs
#=> My name is John Smith
#=> 2

#Third Iteration outputs
#=> How are you?
#=> 3

该类具有一个称为幅度的函数。我想创建一个函数,该函数可以判断两点之间的大小距离。以下是预期的输出:

class Point:
    """Two-Dimensional Point(x, y)"""
    def __init__(self, x=0, y=0):
        # Initialize the Point instance
        self.x = x
        self.y = y

    @property
    def magnitude(self):
        # """Return the magnitude of vector from (0,0) to self."""
        return math.sqrt(self.x ** 2 + self.y ** 2)

    def __str__(self):
        return 'Point at ({}, {})'.format(self.x, self.y)

    def __repr__(self):
        return "Point(x={},y={})".format(self.x, self.y)

我试图做这样的事情:

point1 = Point(2, 3)
point2 = Point(5, 7)
print(point1.magnitude)
    3.605551275463989
print(point2.magnitude)
    8.605551275463989
print(point1.distance(point2))
    5.0

这将返回错误TypeError:distance()接受1个位置参数,但给出2个。我还觉得我对此采取了不正确的方法,因为除了point1或point2之外,其他任何方法都不会起作用。有谁能做得更好?谢谢。

编辑:我做了以下更改:

 @classmethod
    def distance(self):
        pointmag1 = point1.magnitude
        pointmag2 = point2.magnitude
        if pointmag2 > pointmag1:
            return pointmag2 - pointmag1
        else:
            return pointmag1 - pointmag2

这将返回4.996773991578637,而不是5。任何更改此方法的方法吗?

编辑:我进行了以下更改:

 @classmethod
    def distance(self, self2):
        pointmag1 = point1.magnitude
        pointmag2 = point2.magnitude
        if pointmag2 > pointmag1:
            return pointmag2 - pointmag1
        else:
            return pointmag1 - pointmag2

这将返回错误TypeError:'>'在'float'和'property'实例之间不支持

1 个答案:

答案 0 :(得分:0)

您可以实现自定义 if (isConnectedOrConnecting(context)) { //initializeDialog(context) alertDialog!!.dismiss() Log.i("Network","Alive") }else{ alertDialog = dialogBuilder.create() alertDialog!!.show() Log.i("Network","Dead") //initializeDialog(context).create() } } 方法来查找距离:

__sub__

输出:

class Point:
  def __init__(self, x=0, y=0):
    self.x = x
    self.y = y
  @property
  def magnitude(self):
    return math.sqrt(self.x ** 2 + self.y ** 2)
  def __sub__(self, _point):
     return pow(abs(_point.x-self.x)**2 + abs(_point.y-self.y)**2, 0.5)

point1 = Point(2, 3)
point2 = Point(5, 7)
print(point2-point1)

编辑:5.0 实现为方法:

distance