Ádám Bodnár Ádám Bodnár - 3 months ago 8
Python Question

Can't pass a list as class attribute

I have created an iterator. I'm trying to iterate through recipe ingredients, to check if a vegan person can it it, or not.

class Vegan:

NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter']

def __init__(self, *args):
self.ingredient_list = (args)
self.index = -1

def __iter__(self):
return self

def __next__(self):
if self.index == len(self.ingredient_list):
raise StopIteration
for ingredient in self.ingredient_list:
if ingredient in Vegan.NONE_VEGAN_INGREDIENT:
self.index += 1
return ('{} is a vegan ingredient'.format(ingredient[self.index]))
else:
self.index += 1
return ('{} is NOT a vegan ingredient'.format(ingredient[self.index]))

iterable = Vegan('tomato', 'banana', 'asd', 'egg', 'tomato')
iterator = iter(iterable)
while True:
try:
print(next(iterator))
except StopIteration:
break


as you can see, I'm passing *args, which should be a list, but whenever I try to run this, it iterates through the first word, and checks the letters of the word 'tomato'. I want my iterator to go through the ingredients, and if something is not in the NONE_VEGAN_INGREDIENT list, then print as it is in the code. How can I pass in a list?

BPL BPL
Answer

Here's a possible solution to your problem:

class Vegan:

    NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter']

    def __init__(self, *args):
        self.ingredient_list = (args)

    def __iter__(self):
        self.index = 0
        return self

    def __next__(self):
        if self.index >= len(self.ingredient_list):
            raise StopIteration

        ingredient = self.ingredient_list[self.index]
        self.index += 1

        if ingredient in Vegan.NONE_VEGAN_INGREDIENT:
            return ('{} is a vegan ingredient'.format(ingredient))
        else:
            return ('{} is NOT a vegan ingredient'.format(ingredient))

iterable = Vegan('tomato', 'banana', 'asd', 'egg', 'tomato')
iterator = iter(iterable)

while True:
    try:
        print(next(iterator))
    except StopIteration:
        break

In any case, I think this problem could be solved in 1 or 2 lines instead of using __iter__ and __next__ methods like this