你能让一个对象可迭代吗? [重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

我有一些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])

有没有一种巧妙的方法来迭代xy在Python中的某些SomeClass实例?目前迭代我将使用的变量:

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)

谢谢你的帮助!

python python-3.x class iterable
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.