你能让一个对象可迭代吗?
Can you make an object 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 中 SomeClass
的某些实例,是否有一种巧妙的方法来迭代 x
和 y
?目前迭代我将使用的变量:
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__
双下划线方法来做到这一点:
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)
我有一些 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 中 SomeClass
的某些实例,是否有一种巧妙的方法来迭代 x
和 y
?目前迭代我将使用的变量:
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__
双下划线方法来做到这一点:
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)