+ 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)
4 ответов
+ 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]
+ 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.
+ 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])
0
I try it and it responsive
Thanks a lot