类方法麻烦 - Python

时间:2012-04-13 01:33:06

标签: python class math methods definitions

因此在使用类方法时遇到了一些麻烦。我会发布我拥有的所有信息。我需要为给出的问题编写相关的方法。

import math
epsilon = 0.000001
class Point(object):
    def __init__(self, x, y):
        self._x = x
        self._y = y

    def __repr__(self):
        return "Point({0}, {1})".format(self._x, self._y)

第一个问题;我需要添加一个名为disttopoint的方法,该方法将另一个点对象p作为参数并返回两点之间的欧氏距离。我可以使用math.sqrt。

测试用例:

abc = Point(1,2)
efg = Point(3,4)
abc.disttopoint(efg) ===> 2.8284271

第二个问题;添加一个名为isnear的方法,它将另一个点对象p作为参数,如果此点与p之间的距离小于epsilon(在上面的类骨架中定义),则返回True,否则返回False。使用disttopoint。

测试用例:

abc = Point(1,2)
efg = Point(1.00000000001, 2.0000000001)
abc.isnear(efg) ===> True

第三个问题;添加一个名为addpoint的方法,它将另一个点对象p作为一个参数并更改此点,使其为oint的旧值和p的值之和。

测试用例;

abc = Point(1,2)
efg = Point(3,4)
abc.add_point(bar)
repr(abc) ==> "Point(4,6)

3 个答案:

答案 0 :(得分:0)

这里有什么问题?

你坚持创造方法吗?

Class Point(object):
  # make it part of the class as it will be used in it
  # and not in the module
  epsilon = 0.000001

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

  def __repr__(self):
      return "Point({0}, {1})".format(self._x, self._y)

  def add_point(self, point):
      """ Sum the point values to the instance. """
      self._x += point._x
      self._y += point._y

  def dist_to_point(self, point):
      """ returns the euclidean distance between the instance and the point."""
      return math.sqrt(blablab)

  def is_near(self, point):
      """ returns True if the distance between this point and p is less than epsilon."""
      return self.dist_to_point(point) < self.epsilon

这对你有帮助吗?

霍尔迪阿

答案 1 :(得分:0)

class Point(object):
    # __init__ and __repr__ methods
    # ...
    def disttopoint(self, other):
        # do something using self and other to calculate distance to point
        # result = distance to point
        return result

    def isnear(self, other):
        if (self.disttopoint(other) < epsilon):
            return True
        return False

答案 2 :(得分:0)

def dist_to_point(self, point):
      """ returns the euclidean distance between the instance and the point."""
      return math.sqrt(res)

变量“res”应该包含什么?

干杯