+ 3

Class

Can someone explain this code to me? class SpecialString: def __init__(self, cont): self.cont = cont def __truediv__(self, other): line = "=" * len(other.cont) return "\n".join([self.cont, line, other.cont]) spam = SpecialString("spam") hello = SpecialString("Hello world!") print(spam / hello)

27th Feb 2024, 4:23 PM
Artin
Artin - avatar
4 Réponses
+ 4
# You can of course do the same with an ordinary function. def my_owndiv(str_A, str_B): line = "=" * len(str_A) return "\n".join([str_A, line, str_B]) str_A = "spam" str_B = "Hello world!" print(my_owndiv(str_A, str_B)) # Here, the string join method put a newline character \n # between every string element in the list [str_A, line, str_B]
27th Feb 2024, 10:37 PM
Per Bratthammar
Per Bratthammar - avatar
+ 3
Hi, Artin ! This code redefines how the division operator / works for instannces of your SpecialString class, making it behave in your own way. Instead of dividing, it creates a separation betwen the two strings, with a line of = characters. It’s an example of operator overloading. Makes it possible to customize the operators behavor.
27th Feb 2024, 6:07 PM
Per Bratthammar
Per Bratthammar - avatar
+ 1
Oh thanksssss This was my first question to ask publicly inside Solo I did not understand this line in particular return "\n".join([self.cont, line, other.cont])
27th Feb 2024, 6:24 PM
Artin
Artin - avatar
0
I try it and it responsive Thanks a lot
15th Mar 2024, 3:13 PM
Artin
Artin - avatar