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!

2
  • 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, 2019 at 18:45
  • @bison too neat ...
    – ajrlewis
    Mar 21, 2019 at 19:11

1 Answer 1

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)
1
  • Thanks - works a charm ...
    – ajrlewis
    Mar 21, 2019 at 19:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.