Search code examples
pythoniterable

Can I make my class iterable only to use one of its iterable attributes?


As I am making a genetic algorithm, I have a Individu class:

class Individu:
  genotype: List[int]
  code: List[int]
  phenotype: List[List[Client]]
  fitness: float

Most of the time only the attribute genotype is used in the program (for crossing over parents or computing the fitness).

Now, instead of always writing p1.genotype[] when I need to use it, could I make Individu iterable so that I can write p1[] instead or is it a bad idea?

I feel like it would make my program cleaner for me but at the same time could be confusing for others or 'break' some kind of programming best practice.


Solution

  • You seem to be talking about indexing, not iteration per se. Indexing is handled by the __getitem__ method while iteration is handled by __iter__/iter. You could just define these methods for your class to forward the work to the genotype attribute:

    def __getitem__(self, key): return self.genotype[key]
    def __iter__(self): return iter(self.genotype)
    

    Personally I wouldn't do it because this indirection is extra work, probably isn't everything you want to forward to the genotype attribute, and obscures where the iterable really is. But if it fits your use case, then go for it.