这个问题在这里已有答案:
我有一些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])
有没有一种巧妙的方法来迭代x
和y
在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)
谢谢你的帮助!
您可以使用__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)