How to convert an custom class object to a tuple in Python?
如果我们在类中定义
1 2 3 4 5 6 7 8 | class Point(): def __init__(self, x, y): self.x = x self.y = y def __str__(self, key): return '{},{}'.format(self.x, self.y) |
因此我们可以立即将其对象转换为str:
1 2 3 | a = Point(1, 1) b = str(a) print(b) |
但据我所知,没有这样的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> class SquaresTo: ... def __init__(self, n): ... self.n = n ... def __iter__(self): ... for i in range(self.n): ... yield i * i ... >>> s = SquaresTo(5) >>> tuple(s) (0, 1, 4, 9, 16) >>> list(s) [0, 1, 4, 9, 16] >>> sum(s) 30 |
您可以从示例中看到,几个Python函数/类型将以iterable作为参数,并使用它在生成结果时生成的值序列。