jerry-git / learn-python3

Jupyter notebooks for teaching/learning Python 3
MIT License
6.43k stars 1.77k forks source link

I don't understand this code #42

Open Artinflamepurity opened 7 months ago

Artinflamepurity commented 7 months ago

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)

Monalisa0311 commented 1 month ago

Fix: #42

In Python, truediv is used to overload the division operator (/), so when you use / between two SpecialString objects, this method is called instead of performing regular division.

What does it do?:

  1. self.cont: The string inside the first object (on the left of /).
  2. other.cont: The string inside the second object (on the right of /).
  3. line = "=" * len(other.cont) creates a line of equal signs (=) that has the same length as other.cont (the string in the second object).
  4. "\n".join([self.cont, line, other.cont]): This joins three strings: -> self.cont (the first string), -> line (a line of equal signs), -> other.cont (the second string), and puts a newline (\n) between them.

You create two objects: -> spam = SpecialString("spam"): This stores the string "spam" in the cont attribute of the spam object. -> hello = SpecialString("Hello world!"): This stores the string "Hello world!" in the cont attribute of the hello object.

When you use spam / hello, this calls the truediv method and does the following: -> It takes spam.cont, which is "spam". -> It calculates the length of hello.cont, which is "Hello world!", and creates a line of equal signs with that length. Since "Hello world!" is 12 characters long, line becomes "============". -> It joins spam.cont ("spam"), the line of equal signs ("============"), and hello.cont ("Hello world!"), separating them with newlines.

print(spam/Hello) is basically print(spam.truediv(hello))

Final Output: spam

Hello world!