How does Molecule know to reference Atom?

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

Above is the solution to the exercise that asks to give Atom a .__add__(self, other) method that returns a Molecule with the two Atom s.

What i don’t get is in the add method, return Molecule([self, other]), how does Python know what Molecule is? Molecule as a subclass of Atom is defined after the Atom’s class definition. So, why would this code run?


1 Like

The lesson never said Molecule is a subclass. We’re to treat them as unrelated classes. Molecule is an object, very much like integers. Integers can be used plainly, so can Molecule(). When you instantiate Molecule, you are calling it as you would with a regular function that returns a value to you. So Molecule()
is a value to be returned by __add__


Quick check-in, where you said:

Molecule is an object.

I assume you meant class.