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)**
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
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.
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.
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)?
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
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.
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 ?