Dunder methods

my question is that i did not understand the add method in this code:
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)

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

magenta = red.add(blue)
print(magenta).

My question is that what is red.add(blue).Can you explain what is it doing.
and is blue.add(red) same too

@rishikeshupadhya7842

First, please post your code in the Python language, where indentation is mandatory, not optional. To do so, just make use of the </> icon that is in the middle of the menu bar that appears atop a text box when you begin to type:
capture


To become familiar with RGB color mixing, please look here.

Put the code from the Codecademy example into the console screen or your favorite IDE, run it, and then experiment a bit putting the numbers into the above link help you see how the color mixing works.


Now, the lesson is not really about colors; it is about “dunder” methods. The word “dunder” is made up from double underscore, and refers to class methods that are surrounded by a double underscore, like this: __my_method__()

Some dunder methods allow you to write a class method that can be called using a different name or operator than the actual method name. In particular, if your class contains the __add__() method, it can be called using the familiar " + " operator. That is the point of using the __add__() method: it allows you to overload the " + " operator to do something that makes sense in the particular context of the class you are writing.

So, typing red + blue would ordinarily raise a TypeError, but illustrated in the example is a way to code it so that it takes the RGB values of the particular red and blue and mixes them in a certain way. And, as the coder, you control the way that it is done!

2 Likes