1

I have some 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])

is there a neat way to iterate over x and y for some instance of SomeClass in Python? Currently to iterate over the variables I would use:

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

... but can you define SomeClass's behaviour such that the same would work:

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

Thanks for any help!

alexjrlewis
  • 2,717
  • 3
  • 24
  • 58

1 Answers1

2

You can do this with the __iter__ dunder method:


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)
C.Nivs
  • 10,555
  • 2
  • 17
  • 39