Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing __next__ in a custom class

Tags:

python

class

I have a class that looks like this

Class myClass:

    def __init__(self, key, value):
        self.key = key
        self.value = value

where key is a string and value is always a list of elements of myClass, possibly empty.

I want to define my own iter method that returns value.key for each value in values. I tried

def __iter__(self):
    return self 

def __next__(self):
    try:
        self.value.next().key
    except:
        raise StopIteration

but it's looping forever. What am I doing wrong? Also if I want to have Python 2 / 3 compatibility, should I add the method

def next(self):
    return self.__next__()
like image 522
meto Avatar asked Oct 19 '25 05:10

meto


1 Answers

There's no reason for you to implement __next__. You can use __iter__ to return a generator which will do what you want.

class Pair(object):

    def __init__(self, key, value):
        self.key = key
        self.value = value

    def __iter__(self):
        return (v.key for v in self.value)

    # alternative iter function, that allows more complicated logic
    def __iter__(self):
        for v in self.value:
             yield v.key

p = Pair("parent", [Pair("child0", "value0"), Pair("child1", "value1")])

assert list(p) == ["child0", "child1"]

This way of doing things is compatible with both python2 and python3 as the returned generator will have the required next function in python2, and __next__ in python3.

like image 117
Dunes Avatar answered Oct 21 '25 18:10

Dunes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!