【问题标题】:Class method troubles - Python类方法的麻烦——Python
【发布时间】:2012-04-13 01:33:06
【问题描述】:

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

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

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

测试用例:

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)

【问题讨论】:

  • 你不知道怎么办?
  • 你可以用一些额外的 Python 魔法来做:而不是有一个方法 add_point(或者还有它),你可以有 __iadd__;那么你会做abc += bar。根据需要对其他运算符重复(请参阅文档了解它们的含义)

标签: python class math methods definitions


【解决方案1】:
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

【讨论】:

  • 最后一个应该是什么?我想我可以弄清楚前两个,但最后一个我不知道
  • @Hoops 你的意思是 isear 还是 add_point? Jordi 基本上已经展示了如何做 add_point
【解决方案2】:

你的问题是什么?

你是否坚持创建方法?

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

这对你有帮助吗?

乔迪

【讨论】:

  • 我只是对如何将它们结合在一起感到困惑。前两个我想我得到了,最后一个没那么多
【解决方案3】:
def dist_to_point(self, point):
      """ returns the euclidean distance between the instance and the point."""
      return math.sqrt(res)

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

干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多