python - 类来计算球体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)
解决方案
area_of_sphere
根本不应该在那里。这与上课的整个想法背道而驰。
该Point.__eq__
方法有效,因此您可以编写
p1 = Point(...)
p2 = Point(...)
if p1 == p2: ...
否则,默认行为==
是检查它们是否是同一个对象,它会返回 false。
推荐阅读
- c++ - scanf() 语句中的格式字符串“%*[^\n]”有什么指示?分配抑制器 (*) 和否定扫描集 ([^) 如何协同工作?
- bash - sed remove trailing slash from url
- android - Android HERE SDK - 示例应用未替换 app_id 和 app_code
- excel - VBA在插入单元格时更改数字十进制数
- c# - Unity:动画事件不会改变动画对象的变换
- bluetooth - 多个连接上的蓝牙 5 和 BLE 吞吐量
- python - 如何在按钮内获取html元素?
- java - 将 JSON 字符串映射到 HashMap
- php - Laravel 5.7 中的 auth 和 access 有什么区别?
- python - 如何使用 Pandas 从某个时间戳获取 date_range?