Home > Software engineering >  Argument of class is not iterable
Argument of class is not iterable

Time:12-15

So I'm trying to replicate the Enigma Machine, and one of the things I'm trying to make is the Plugboard. So the class PlugLead is meant to establish a connection between two letters. Plugboard has two functions, add (which adds the connection between two letters to the Plugboard) and encode gets the linked letter.

class PlugLead:
  def __init__(self, mapping):
    self.mapping = mapping

  def __str__(self):
    return self.mapping

  def __repr__(self):
    return self.mapping

  def encode(self, character):
    leads = self.mapping

    if character not in leads:
      return character
    else:
      if character == leads[0]:
        return leads[1]
      else:
        return leads[0]
    return leads
class Plugboard:

  def __init__(self):
    self.arr = []

  def __str__(self):
    return (f'Mapping:{self.arr}')

  def __repr__(self):
    return (f'Mapping:{self.arr}')

  def add(self,connection):
    self.arr.append(connection)

  def encode(self,letter):
    for i in range(0,len(self.arr)-1):
      if letter in self.arr[i]:
        return self.arr[i].replace(letter, '')
    raise ValueError("Character can not be encoded")
plugboard = Plugboard()
plugboard.add(PlugLead("AR"))
plugboard.add(PlugLead("BT"))
assert(plugboard.encode("A") == "R")

I get the error:

TypeError: argument of type 'PlugLead' is not iterable

So I think I get that PlugLead(string) doesn't return a string, but I'm not sure how to get it to return a string so I can use it in other classes.

CodePudding user response:

You can implement a __contains__() method in your class so that the in operator is implemented.

class PlugLead:
  def __init__(self, mapping):
    # Your code here
    self.mapping = mapping 

  def __str__(self):
    return self.mapping 

  def __repr__(self):
    return self.mapping

  def __contains__(self, item):
    return item in self.mapping

  def encode(self, character):
    leads = self.mapping
        
    if character not in leads:
      return character
    else:
      if character == leads[0]:
        return leads[1]
      else:
        return leads[0]
    return leads

CodePudding user response:

Thanks everyone for the help. I managed to get it working.

So I had to get the object mapping from PlugLead and not the class itself so it's actually

def encode(self,letter):
  for item in self.arr:
    if letter in item:
      a = PlugLead(item.mapping)
      return a.encode(letter)

And I use the encode function from PlugLead to actually encode it

  • Related