samedi 27 juin 2015

Puthon 2.7: Comparison method, compairing 2 points returning boolean value [duplicate]

This question already has an answer here:

I am using an equality method to compare the x and y coordinates of a point to another point, returning a boolean value. If the points have the same x and y coordinates, I want to return True, otherwise, I want to return False.

class Point(Geometry):
    def __init__(self,x,y):
        Geometry.__init__(self,id=0)
        self.x = x
        self.y = y

    def __str__(self):
        return'x = %.2f,y = %.2f'%(int(self.x*100)/100.0,int(self.y*100)/100.0)


    def __eq__(self,p1,p2):
        if p1 == p2: #boolean method?
            return True
        else:
            return False

Output:

>>>p1 = Point(-2,1)
>>> p2 = Point(1,5)
>>> print p1
x = -2.00,y = 1.00
>>> print p2
x = 1.00,y = 5.00
>>> p1.equal(p2)

Error:

p1.equal(p2) AttributeError: 'Point' object has no attribute 'equal'

I was expecting a True or False but I must not be using the comparison method properly. Should there b another if statement in place of the if not condition? Such as:

if p1!=p2:
    return False

Aucun commentaire:

Enregistrer un commentaire