Home > Software design >  Compare two String by length only in a special class using __eq__?
Compare two String by length only in a special class using __eq__?

Time:03-04

I'm trying to create a Class to compare two String only by length (using the Magic method). Here is my code:

class CustomString:
    def __init__(self,string):
        self.string=string
        
    def __eq__(self,other):
        if len(self.string) == len(other.string):
            return True
        else:
            return False
spam = CustomString('spam')
eggs = CustomString('eggs')

spam==eggs

I don't know where is wrong but in the end, it returned nothing at all. My IDE also said that "Statement appears to have no effect" at the spam=eggs line. I also need to write __gt__ and __lt__, but I think I need to understand how __eq__ work first.

I really appreciate it if someone could show me what is wrong. Thank you in advance!

CodePudding user response:

Your code is correct but you forget to add a print function. It should be print(spam==eggs) just like print(1==1)

CodePudding user response:

Thank you, everyone! I just forgot to add a print function. Just add print(spam==eggs) work.

  • Related