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!

A post was split to a new topic: How can I use __add__ with more than 2 objects?

3 posts were split to a new topic: How does Molecule know to reference Atom?

13 posts were split to a new topic: How can I use string representation to print the combined molecule?

6 posts were split to a new topic: How do I know they want a list?

Hi, I would like to ask some questions regarding the example before this exercise.
In the example, in particular this part:

def add(self, other):
** “”"**
** Adds two RGB colors together**
** Maximum value is 255**
** “”"**
** new_red = min(self.red + other.red, 255)**
** new_blue = min(self.blue + other.blue, 255)**
** new_green = min(self.green + other.green, 255)**

** return Color(new_red, new_blue, new_green)**

  1. why type of variables are the new_red, new_blue and new_green variables? I thought that only instance variables can be declared under a method, in that case, these variables must be written as self.new_red, self.new_blue, self.new_green
  2. Can you explain to me what do these variables other.red, other.blue and other.green do in the method? These variables are not declared before in the method so there should be a bug happen, right?

The whole Classes lesson is really confusing for me.

Thank you.

5 Likes
class Color:
  def __init__(self, red, blue, green):
    self.red = red
    self.blue = blue
    self.green = green

  def __repr__(self):
    return "Color with RGB = ({red}, {blue}, {green})".format(red=self.red, blue=self.blue, green=self.green)

  def add(self, other):
    """
    Adds two RGB colors together
    Maximum value is 255
    """
    new_red = min(self.red + other.red, 255)
    new_blue = min(self.blue + other.blue, 255)
    new_green = min(self.green + other.green, 255)

    return Color(new_red, new_blue, new_green) #This is the mistake here.

red = Color(255, 0, 0)
blue = Color(0, 255, 0)

magenta = red.add(blue)
print(magenta)
# Prints "Color with RGB = (255, 255, 0)"

This code while correct, has a mistake in order. This code returns RBG not RGB, might be worthwhile to fix.

@alyssavigil, this appears to be a quick and easy edit. The example given in the lesson clearly defines blue incorrectly. It should be,

blue = Color(0, 0, 255)

so that magenta prints as (255, 0, 255).

Why don’t we need to use self when defining new_red, new_blue, and new_green in the addition method?

e.g. self.new_red where as the example just uses new_red.

Because they are not instance attributes, but running variables. We return a new Color object using those variables.

1 Like

Thanks very much – would it work the same if we treated them as instance variables vs running variables?

Is it just up to the programmer whether they want a variable to be an attribute (instance variable) vs just a running variable?

1 Like

You’re welcome, @codemoose65.

It would alter the makeup of the class, and would be unnecessary. The variables are local to the add method and don’t need to be saved.

Yes, and no. The class we are wanting to implement should have only the attributes and methods that each instance needs. They don’t need new_red, etc. Let those be local variables that are garbage collected when the method is finished running.

Totally get it! Your prompt response and clarity are much appreciated - especially for a challenging concept like this.

1 Like

Hi all,

Got another question for this module:

After we provide the “correct” code to go to the next exercise, the class Atom is defined before the class Molecule. Yet, within Atom there are references made to the class Molecule. Why wouldn’t python raise an error here (since we’re referencing to class we have not defined before that point in the code)?

2 Likes

Hello @mtf ! I need your help again. Here is my code

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

  def __add__(self, other):
    return Molecule([self.label, other.label])
    
class Molecule:
  def __init__(self, atoms):
    if type(atoms) is list:
	    self.atoms = atoms
    print(self.atoms)

  def __repr__(self):
    molecular_formula = " "
    for index in range(len(self.atoms)):
      molecular_formula += salt.atoms[index]
    return molecular_formula
      
sodium = Atom("Na")
chlorine = Atom("Cl")
#salt = Molecule([sodium, chlorine])
salt = sodium + chlorine
print(salt)

1. I don’t understand how is class Molecule is being instantiated ? is it because I’m returning Molecule([self.label, other.label]) ? if so then don’t I have to refer to some object like
#salt = Molecule([sodium, chlorine]) in order to do so ?

2. what actually __add__ method doing here ?
please explain in layman’s terms

exercise link

https://www.codecademy.com/courses/learn-python-3/lessons/inheritance-and-polymorphism/exercises/dunder-methods

Not quite sure I can jump on board, just yet. Can you post a link to the exercise so we get more context? Thanks.

It is interpreting the + operation in,

salt = sodium + chlorine

We need to see lesson to confirm your method. Bit foggy, just now.

1 Like

https://www.codecademy.com/courses/learn-python-3/lessons/inheritance-and-polymorphism/exercises/dunder-methods

here is the exercise link

1 Like

Okay, now I see why it was a bit confusing. The .label attribute was throwing me off.

To build a Molecule object we need to pass it two Atom objects. In the return expression above, you are passing only strings, where you should be passing instances.

return Molecule([self, other])
1 Like

ok. so is it making ‘Na’+ ‘cl’ = Nacl ? if so then Why do I need to implement __repr__ method and iterate through a list to print the string representation ‘Nacl’ ? can’t I just print salt after adding the two ?

could explain a little bit more how it is effecting my code ? isn’t it getting same value ?