__add__ question

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")
print(sodium + chlorine)

salt = Molecule([sodium, chlorine])
# salt = sodium + chlorine

The part I don’t understand is “return Molecule([self, other])” this line. Here Molecule class is not yet defined, but how could class atom attribute return Molecule([self, other])?

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

doesn’t happen until you call it, at which point it exists