学习OOP(课程)

时间:2012-12-28 17:46:50

标签: python oop class geometry points

我已经达到了一个好点,但我仍然需要: 定义一个等式方法来比较另一个点的x和y坐标 ─如果两个点具有相同的x和y坐标,则返回True。否则,返回False  用于比较另一个点的id的标识方法 ─如果两点的ID相同,则返回True。否则,返回False  通过方法参数测量从当前到另一个点的距离的方法。

我只是对如何存储第一个点与另一个点进行比较感到困惑。

这是我到目前为止所做的:

class Geometry(object):

    control_id=0
    def __init__(self):
        self.control_id+=1
        self.id=control_id

class Point(object):
    def __init__(self, x, y):
        self.x=float(x)
        self.y=float(y)
    def __repr__(self):
        return "Point object at: (%s, %s)" % (self.x, self.y)

p1 = Point(1.216, 3.4582)
print p1

result: Point object at: (1.216, 3.4582)

2 个答案:

答案 0 :(得分:1)

您已将您的继承和实例变量分配混淆。

尝试更简单的方法:

from math import sqrt

class Point(object):  
    def __init__(self, y, x):
        self.x = float(x)
        self.y = float(y)

    def __repr__(self):
        return "Point object at: (%s, %s)" % (self.y, self.x)

    def __cmp__(self, point):
        """compare two points via ==, <, >, and so on"""
        return cmp(self.dist_from_origin(), point.dist_from_origin())

    def dist_from_origin(self):
        """Euclidean distance of a point from (0, 0)"""
        return math.sqrt( ) #your work goes here...

一旦得到这么多,请尝试转到Line对象,该对象需要两个Point个实例并指定一个m属性,表示斜率。然后,尝试使用__len__为该行实现this formula函数。

编辑:

就你的id问题而言,Python为它创建的每个对象分配一个id ...但是,这并不意味着对象是相同的&#34;拥有相同的身份。

>>> a = Point(2, 2)
>>> b = Point(2, 2)
>>> a == b
True
>>> a is b
False
>>> id(a), id(b)
(41217048L, 41216824L)
>>> c = a
>>> c is a
True
>>> id(a), id(c)
(41217048L, 41217048L)

正如您所看到的,a == b表示它们是相同的...... 距离原点的距离

您可能想要创建一个比较两个Point实例的方法。 xy属性,如果两个点具有相同的坐标,则返回True。至于你有id的问题?只需使用内置id()函数。

答案 1 :(得分:1)

应该明确引用类似超类中全局计数器的静态字段:Geometry.counter

此实现计算两点之间的距离Manhattan距离:

import operator

class Geometry(object):

    counter=0

    def __init__(self):
        super(Geometry, self).__init__()
        Geometry.counter += 1
        self.ID = Geometry.counter


class Point(Geometry):

    def __init__(self, x, y):
        super(Point, self).__init__()
        self.x, self.y = (float(x), float(y))

    def __repr__(self):
        return "(%d, %d)" % (self.x, self.y)

    def __eq__(self, point):
        if type(point) is Point:
            if self.x == point.x:
                if self.y == point.y:
                    return True
        return False

    def dist(self, point):
        if type(point) is Point:
            return sum(map(operator.abs, map(operator.sub, 
                [self.x, self.y], [point.x, point.y])))
        else:
            return None

输出:

>>> p=Point(2,4)
>>> q=Point(1,5)
>>> p.dist(q)
2.0
>>> p == q
False
>>> q.ID
4
>>> p
(2, 4)