我有一些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
的某些实例,是否有一种整洁的方法来遍历y
和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)
感谢您的帮助!
答案 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)