FAQ: Learn Python: Inheritance and Polymorphism - Dunder Methods

salt is a Molecule instance which .atoms attribute is a list of Atom instances. It’s necessary to iterate the list so that we can extract each object’s .label attribute. The __repr__() method helps us create the final representation.

1 Like

thanks, I’ll try and see what happens

Hi all, would like some help to understand why my code is rejected by the exercise. I realise my code is less succinct but am not sure why it is wrong. The question and my code are below. Help is much appreciated

In script.py there are two classes defined, Atom and Molecule.

Give Atom a .__add__(self, other) method that returns a Molecule with the two Atoms together in a list.

My code

class Atom:
  def __init__(self, label):
    self.label = label
  def __add__(self, other):
    first_atom = [self.label]
    second_atom = [other.label]
    molecule_list = first_atom + second_atom
    return Molecule(self, molecule_list)

    
class Molecule:
  def __init__(self, atoms):
    if type(atoms) is list:
	    self.atoms = atoms
  
      
sodium = Atom("Na")
chlorine = Atom("Cl")
salt = Molecule([sodium, chlorine])
# salt = sodium + chlorine

Solution

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
      
sodium = Atom("Na")
chlorine = Atom("Cl")
salt = Molecule([sodium, chlorine])
# salt = sodium + chlorine

That is not using the dunder method (__add__). It gets called when we use the plus sign in,

salt = sodium + chlorine

We don’t combine them in the Atom class. Your __add__() method never runs.

“that’s only scratching the tip of the iceberg.”

Best mixed metaphor I’ve heard in a long time!!