FAQ: Learn Python: Inheritance and Polymorphism - Dunder Methods

This community-built FAQ covers the “Dunder Methods” exercise from the lesson “Learn Python: Inheritance and Polymorphism”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

FAQs on the exercise Dunder Methods

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

What would add look like if I would like to add > 2 objects?

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?


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__


What I don’t understand is how making the __add__ method return Molecule([self, other]) “returns a Molecule with the two Atom s” like the exercise tells us to do. I’ve tried uncommenting the comment in line 16 and printing out salt but all that’s printed out is “<main.Molecule object at 0x7f66084df6a0>”. How is “<main.Molecule object at 0x7f66084df6a0>” a molecule with the two atoms? ;-;

Do you have reason to expect any other output?
Perhaps you might write code which causes a different string representation of your object.

I was expecting the output to be “NaCl”, as it’s a molecules with 2 atoms (I think). This was my initial solution to the exercise:

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

def add(self, other):
return self.label + other.label

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

“NaCl” gets printed to the console. But this wasn’t the right answer. My question now is how is the answer presented by codecademy a molecule with 2 atoms?

In order to expect that output there would need to be code which writes those specific characters to stdout. There’s not. So no reason to expect it. The number of atoms wouldn’t affect this. You could print out an atom and get a similar result, again, no code that is doing string formatting for that.

What affects the string representation of an object?

Oh I get it now. repr() is the method responsible for the string representation of an object not add(), so my solution was definitely wrong. And by making add() return Molecule([self, other]) we are literally returning a molecule with 2 atoms.

Thanks a lot for taking your time to reply. I was afraid no one would answer at first :sweat_smile:

Try add the following code inside of the Molecule class as the dunder method. Then try to print your “:salt:”.

def __repr__(self):
  molecular_formula = ""
  for index in range(len(self.atoms)):
    molecular_formula += salt.atoms[index].label
  return molecular_formula
1 Like

I don’t understand anything about this code. What is it doing? What does " Give Atom a .__add__(self, other) method that returns a Molecule with the two Atom s." even mean? How do I test this code to see what each step is doing?

An __add__ method within a class is a method that can be called on an instance of the class just by using the + operator. You can define to do anything that you would like the + operator to do within your class.

class MiddleSchool:
    def __init__(self, name):
        self.name = name
    def __add__(self, other):
        return "{} loves {}, ha ha!!!".format(self.name, other)    
paul = MiddleSchool("Paul")
print(paul + "Maria")

# Output:
Paul loves Maria, ha ha!!!
1 Like

Thanks Patrick!
I am really confused with the question itself. " Give Atom a .__add__(self, other) method that returns a Molecule with the two Atom s.". After seeing the answer I get that they want a Molecule object returned with a list of the two Atom objects in a list. Is it common in programmer “lingo” to say return “x” with “number” of “y” and have that mean to return the ""y"s in a list?

No; the assignment could have been phrased more clearly. They could have expected a string or a tuple, for all you knew. The point to remember is that in your class, you can make + do anything you want!

For a challenge, you could code it so that ‘carbon’ + ‘oxygen’ + ‘oxygen’ returns ‘CO2’.

Thank you! I would give you a tip if i could!

1 Like

Yeh this lesson is totally not the best one. And excersice is super weird. At first I didn’t even understand what exactly they want us to make. My first solution was more like @theworldcup.

@Codecademy edit this lesson please :slight_smile: Make it more understandable.

This should definitely be added as a second task for this exercise, thank you!