注释:下面代码演示了如何让代码更抽象,更有应对变化的可能。下面(1)(2)(3)(4)(5)都是被否定的写法,也是一些初学者容易写出的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Vector2d(): def __init__(self, x, y): self.x = x self.y = y def __iter__(self): return (i for i in (self.x, self.y)) def __repr__(self): class_name = type(self).__name__ return '{}({!r}, {!r})'.format(class_name, *self) def __eq__(self, other): return tuple(self) == tuple(other)
def __str__(self): return str(tuple(self.x, self.y))
|
这个系列未完待续…