简体   繁体   中英

Trying to Understand This Line in the Code

I'm kinda new to Python, and just got into Object Oriented. I think I understand the basic but this line of code has really got me confused.

Here's the entire piece:

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)

I'm talking about the this one:

line = "=" * len(other.cont)

I don't get what 'other.cont' mean. How can an object be an attribute of another object? Or is 'cont' just being applied on 'other'?

The truediv () special method is only used with the / operator.

Below is how i can breakdown the truediv . This is basically known as operator overloading.

def __truediv__(self, SpecialString("Hello world!")):
    #line = "=" * len(other.cont)
    line = "=" * len(SpecialString("Hello world!").cont)

    #return "\n".join([self.cont, line, other.cont])
    return "\n".join([SpecialString("spam").cont, line, SpecialString("Hello world!").cont])

Other here is the 2nd class instance that is being passed.

There is a question in SO which answers operator overloading of truediv ()in detail. You can check it here: operator overloading for __truediv__ in python

The method expects two object instances as parameters, self and other . The code doesn't care as such which class other belongs to, as long as it has a cont attribute, too, which has a length. But the division method commonly takes two objects of the same type.

(When an object of a different type behaves the same as yours, that's called polymorphism. This isn't crucial to understand at this point, but you've probably come across the concept.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM