Search code examples
pythonooprepr

Python TypeError: must be str, not Atom


Can someone tell me in beginner friendly way why am I not being able to print the Molecule name (here in this case 'NaCl') ? if I replace return Molecule([self, other]) with return Molecule([self.label, other.label]) my code works and produces the expected output but I want to pass instances and not attributes. here is my code:

class Atom:
  def __init__(self, label):
    self.label = label

  def __add__(self, other):
    return Molecule([self, other])
    
class Molecule:
  def __init__(self, atoms):
    if type(atoms) is list:
        self.atoms = atoms
      
  def __repr__(self):
    lol = ''
    for i in self.atoms:
      lol += i
    return lol

sodium = Atom("Na")
chlorine = Atom("Cl")
salt = Molecule([sodium, chlorine])
salt = sodium + chlorine
print(salt)

here is the exercise image: my problem


Solution

  • Your trace is telling you what line you need to look at. Line 14 you have this

    lol += i
    

    Python is struggling with this cause first lol is a string. We know that cause you assigned it this with lol = ''

    but now you're asking Python to append an instance of Atom to the str. However you haven't told Python how it's supposed to append a type of Atom to a str.

    So you have two options here.

    1. In your Atom class, override the __repr__ function and then convert i to a string.

    2. In your Molecule class, append to lol with i.label rather than just i