首页 > 解决方案 > 类来计算球体Python的面积

问题描述

我正在查看计算球体面积的代码,我注意到他们使用了_eq_。我知道它用于检查相等性,但我想知道在这个例子中需要它什么?


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)


标签: pythongeometry

解决方案


area_of_sphere根本不应该在那里。这与上课的整个想法背道而驰。

Point.__eq__方法有效,因此您可以编写

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

if p1 == p2: ...

否则,默认行为==是检查它们是否是同一个对象,它会返回 false。


推荐阅读