您可以使对象迭代吗?

时间:2019-03-21 18:23:37

标签: python python-3.x class iterable

我有一些class

import numpy as np

class SomeClass:
    def __init__(self):
        self.x = np.array([1,2,3,4])
        self.y = np.array([1,4,9,16])

对于Python中x的某些实例,是否有一种整洁的方法来遍历ySomeClass?当前要遍历我将使用的变量:

some_class = SomeClass()
for x, y in zip(some_class.x, some_class.y):
    print(x, y)

...但是您是否可以定义SomeClass的行为,使其同样起作用:

some_class = SomeClass()
for x, y in some_class:
    print(x, y)

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您可以使用__iter__ dunder方法执行此操作:


class SomeClass:
    def __init__(self):
        self.x = np.array([1,2,3,4])
        self.y = np.array([1,4,9,16])

    def __iter__(self):
        # This will yield tuples (x, y) from self.x and self.y
        yield from zip(self.x, self.y)

for x, y in SomeClass():
   print(x,y)