Myaccount
Myaccount

Reputation: 79

class to calculate area of sphere Python

I was looking at a code to calculate area of sphere and I noticed they used _ eq _. I know it's used to check equality, but I am wondering what is the need for it in this example?


class Point3d:
......

    def distance_from_origin(self):
        temp_x = self.x ** 2
        temp_y = self.y ** 2
        temp_z = self.z ** 2
        return ((temp_x) + (temp_y) + (temp_z)) ** 0.5 

    def area_of_sphere(self):
        return (4 * math.pi * (self.distance_from_origin())**2)

    def __eq__(self, object):
        if self.x == object.x and self.y == object.y and self.z == object.z:
            return True
        else:
            return False

    def __str__(self):
        return str(self.x) + " , " + str(self.y) + " , " + str(self.z)


Upvotes: 0

Views: 156

Answers (2)

user1196549
user1196549

Reputation:

I suspect that this is a requirement of a uniform API, which systematically includes an equality operator as well as a string formatter.

They are of strictly no use to compute the area. One may even question if a class is needed at all for such an elementary formula. (By the way, there is a sad loss of efficiency caused by the fact that you take a square root then square back.)

Upvotes: 0

blue note
blue note

Reputation: 29099

The area_of_sphere should not be there at all. That goes against the whole idea of having a class.

The Point.__eq__ method works so that you can write

p1 = Point(...)
p2 = Point(...)

if p1 == p2: ...

otherwise, the default behavior of == would be to check if they are the same object, and it would return false.

Upvotes: 3

Related Questions