python-3.x - 以下代码中的“s or s[0] in Yy”是什么?
问题描述
在以下使用 python 的代码中, def __sub__()
and def __eq__()
are or are not 被使用?我习惯于variableObject.action
在 say中看到这些my_dog.sit()
。但是,对于双下划线,只需调用 . 似乎是固有的class Point3D()
,这可能在def is_win()
.
我也很难阅读这个特别 while not s or s[0] in Yy
的,因为它的 [0] 似乎表明只是进入退出而不进入循环。此外,我不知道如何在Yy
这里使用它。
我试过输入s[1]
,它说索引超出范围,确认输入退出。它不应该简单地阅读while not s[0]
更清晰的代码吗?
class Point3D:
'''Three dimensional point class, supporting
subtraction and comparison. '''
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __sub__(self, other):
d1 = self.x - other.x
d2 = self.y - other.y
d3 = self.z - other.z
return Point3D(d1, d2, d3)
def __eq__(self, other):
return(self.x == other.x and self.y == other.y
and self.z == other.z)
def main():
s = ''
while not s or s[0] in 'Yy':
p1 = get_point()
p2 = get_point()
p3 = get_point()
if is_win(p1,p2,p3):
print('is a winning combination.')
else:
print('Is not a win.')
s = input('Do again(Y or N)?')
def get_point():
s = input('Enter point x, y, z format:')
ls = s.split(',')
x, y, z = int(ls[0]), int(ls[1]), int(ls[2])
return Point3D(x,y,z)
def is_win(p1,p2,p3):
if(p3-p2 == p2 - p1
or p2-p3 == p3-p1
or p3-p1 == p1-p2):
return True
else:
return False
main()
解决方案
__sub__
和都是__eq__
python 类中的“特殊”方法。每当您比较同一类的两个对象时,您都会使用__eq__
、__gt__
或中的一个__lt__
。__eq__
只不过是==
。因此,当您p1 == p2
使用该__eq__
方法时。同样,__sub__
是减法。当你p1 - p2
使用__sub__
. 您不会像使用其他方法一样使用这些方法。你不 p1.__sub__(p2)
。
第二部分是你在等待s
成为y
or Y
。
推荐阅读
- android - 如何从 Java 程序调整 Android 网格布局间距
- string - 如何确定字符串的最小公约数?
- bonita - 启动后修改 Bonita 进程实例
- flutter - 在 Flutter 应用中集成 Paypal 支付
- c++ - DrawShadow 中的 Elevation 到底是做什么的?
- angular - 在 NativeScript Angular 中设置 SuggestionView 宽度的任何方式
- ubuntu - fail2ban apachefakegooglebot 失败正则表达式位置
- python - 我的 Discord XP 机器人无法识别 JSON 文件中的用户数据?
- java - @JsonFormat 不适用于自定义序列化程序
- javascript - 用于加载 HTML 文件的 JQuery 函数调用不起作用