FAQ: Learn Python: Inheritance and Polymorphism - Dunder Methods


#1

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!


#2

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


#3
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?

Thanks


#4

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__