Anyone explain this clearly ? Thank you | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

Anyone explain this clearly ? Thank you

class SpecialString: def __init__(self, cont): self.cont = cont def __gt__(self, other): for index in range(len(other.cont)+1): result = other.cont[:index] + ">" + self.cont result += ">" + other.cont[index:] print(result) spam = SpecialString("spam") eggs = SpecialString("eggs") spam > eggs

6th Jul 2017, 4:36 PM
Edu Rut
Edu Rut  - avatar
1 Resposta
0
The idea is this. When you make a class you have an instance of that object. So in the case above you have two separate items; eggs and spam. When you create the two items, the variable cont is set inside the class. Now if I had this function call outside the class (let's assume it performs the same operation); def dothis(first, second): To call this function I would have to write it like this; dothis(eggs.cont, spam.cont) While in this case, it isn't very complex you could easily do this function instead of the magic method. What the Magic Method does, is allows for an interaction between the two classes that you can't do in a normal method. In the above example ignore __gt__ , the operator is only used to trigger the event (which is what I think makes this more confusing). So instead of passing the values by pulling them out of the class, the magic method allows you to have the values interact within the class. So let's add another method that changes the value of one of the values. I'll use the __add__ method. def __add__(self, other): other.cont = "{} and {}!".format(self.cont, other.cont) To call this I only need to run spam + eggs Using the plus sign(+) between the two classes activates the __add__ method. If I called this from a normal function, I might have to ( or should) use setters to change a class value outside of the class. This becomes more powerful when you have a lot of variables from the classes that you want to interact with each other and/or variables that you have protected from being changed outside of the class. So what is confusing about their example is that it uses the > operator and then they use it as a string to create an effect. Just know the intent is to let classes talk to each other on their own level. I hope this helps.
8th Jul 2017, 2:28 PM
Jim Tully
Jim Tully - avatar