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!

ajrlewis
  • 2,968
  • 3
  • 33
  • 67
  • If you want a 'neat way' -> `for i in SomeClass(np.array([1,2,3,4]), np.array([1,4,9,16])):` ``` class SomeClass(zip): def __new__(cls, *args): return zip.__new__(cls, *args) ``` – bison Mar 21 '19 at 18:45
  • @bison too neat ... – ajrlewis Mar 21 '19 at 19:11

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
  • 12,353
  • 2
  • 19
  • 44