How can I use string representation to print the combined molecule?

One finds it difficult to believe that in the advanced stage we find ourselves (classes) that list and str methods would not have been covered, along with a host of other built-ins, but you raise a good point. Your approach is the more naive of the two, which is something I tend to encourage in learners.

I used to teach IT at a college level (i.e. part-time night classes). The hardest thing to do is to talk to the level of the student is at. It’s so much more fun to throw out something totally new to them and watch the perplexed look. But the downside is it doesn’t reinforce what they have learned to that point or give them confidence in what they have accomplished so far.


Thank you for answering the question, unlike every other commentor on this entire module who has taken it upon themselves to be completely obtuse.

Although that solution works, I think this is simpler:

class Atom:
  def __init__(self, label):
    self.label = label
  def __repr__(self):
    return self.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):
    return str(self.atoms)

This also preserves the class structure - since a Molecule object is a list of Atom objects, it makes sense that printing a Molecule object should print a string representation of the list of atoms, and it also makes sense that printing an Atom object should print the label of that atom.

This lesson ABSOLUTELY needs to incorporate a way to review what is happening in this code by teaching us how we should be seeing an output properly. The good folks in this thread who are actually smart enough to know this stuff have solved this issue but I see the teaching in this forum as ESSENTIAL to this subject matter.

This lesson is half baked and serves only to further confuse an already tricky premise.