首页 > 解决方案 > 以下代码中的“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()

标签: python-3.x

解决方案


__sub__和都是__eq__python 类中的“特殊”方法。每当您比较同一类的两个对象时,您都会使用__eq____gt__或中的一个__lt____eq__只不过是==。因此,当您p1 == p2使用该__eq__方法时。同样,__sub__是减法。当你p1 - p2使用__sub__. 您不会像使用其他方法一样使用这些方法。你 p1.__sub__(p2)

第二部分是你在等待s成为y or Y


推荐阅读